es6.js 4.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592
  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 The current define statements for the shader.
  65. * @returns The resulting defines with defines of the current rank removed.
  66. */
  67. EffectFallbacks.prototype.reduce = function (currentDefines) {
  68. // First we try to switch to CPU skinning
  69. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  70. this._mesh.computeBonesUsingShaders = false;
  71. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  72. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  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 === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  77. otherMesh.computeBonesUsingShaders = false;
  78. }
  79. }
  80. }
  81. else {
  82. var currentFallbacks = this._defines[this._currentRank];
  83. if (currentFallbacks) {
  84. for (var index = 0; index < currentFallbacks.length; index++) {
  85. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  86. }
  87. }
  88. this._currentRank++;
  89. }
  90. return currentDefines;
  91. };
  92. return EffectFallbacks;
  93. }());
  94. BABYLON.EffectFallbacks = EffectFallbacks;
  95. /**
  96. * Options to be used when creating an effect.
  97. */
  98. var EffectCreationOptions = /** @class */ (function () {
  99. function EffectCreationOptions() {
  100. }
  101. return EffectCreationOptions;
  102. }());
  103. BABYLON.EffectCreationOptions = EffectCreationOptions;
  104. /**
  105. * Effect containing vertex and fragment shader that can be executed on an object.
  106. */
  107. var Effect = /** @class */ (function () {
  108. /**
  109. * Instantiates an effect.
  110. * An effect can be used to create/manage/execute vertex and fragment shaders.
  111. * @param baseName Name of the effect.
  112. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  113. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  114. * @param samplers List of sampler variables that will be passed to the shader.
  115. * @param engine Engine to be used to render the effect
  116. * @param defines Define statements to be added to the shader.
  117. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  118. * @param onCompiled Callback that will be called when the shader is compiled.
  119. * @param onError Callback that will be called if an error occurs during shader compilation.
  120. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  121. */
  122. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  123. if (samplers === void 0) { samplers = null; }
  124. if (defines === void 0) { defines = null; }
  125. if (fallbacks === void 0) { fallbacks = null; }
  126. if (onCompiled === void 0) { onCompiled = null; }
  127. if (onError === void 0) { onError = null; }
  128. var _this = this;
  129. /**
  130. * Unique ID of the effect.
  131. */
  132. this.uniqueId = 0;
  133. /**
  134. * Observable that will be called when the shader is compiled.
  135. */
  136. this.onCompileObservable = new BABYLON.Observable();
  137. /**
  138. * Observable that will be called if an error occurs during shader compilation.
  139. */
  140. this.onErrorObservable = new BABYLON.Observable();
  141. /**
  142. * Observable that will be called when effect is bound.
  143. */
  144. this.onBindObservable = new BABYLON.Observable();
  145. this._uniformBuffersNames = {};
  146. this._isReady = false;
  147. this._compilationError = "";
  148. this.name = baseName;
  149. if (attributesNamesOrOptions.attributes) {
  150. var options = attributesNamesOrOptions;
  151. this._engine = uniformsNamesOrEngine;
  152. this._attributesNames = options.attributes;
  153. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  154. this._samplers = options.samplers;
  155. this.defines = options.defines;
  156. this.onError = options.onError;
  157. this.onCompiled = options.onCompiled;
  158. this._fallbacks = options.fallbacks;
  159. this._indexParameters = options.indexParameters;
  160. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  161. if (options.uniformBuffersNames) {
  162. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  163. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  164. }
  165. }
  166. }
  167. else {
  168. this._engine = engine;
  169. this.defines = defines;
  170. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  171. this._samplers = samplers;
  172. this._attributesNames = attributesNamesOrOptions;
  173. this.onError = onError;
  174. this.onCompiled = onCompiled;
  175. this._indexParameters = indexParameters;
  176. this._fallbacks = fallbacks;
  177. }
  178. this.uniqueId = Effect._uniqueIdSeed++;
  179. var vertexSource;
  180. var fragmentSource;
  181. if (baseName.vertexElement) {
  182. vertexSource = document.getElementById(baseName.vertexElement);
  183. if (!vertexSource) {
  184. vertexSource = baseName.vertexElement;
  185. }
  186. }
  187. else {
  188. vertexSource = baseName.vertex || baseName;
  189. }
  190. if (baseName.fragmentElement) {
  191. fragmentSource = document.getElementById(baseName.fragmentElement);
  192. if (!fragmentSource) {
  193. fragmentSource = baseName.fragmentElement;
  194. }
  195. }
  196. else {
  197. fragmentSource = baseName.fragment || baseName;
  198. }
  199. var finalVertexCode;
  200. this._loadVertexShaderAsync(vertexSource)
  201. .then(function (vertexCode) {
  202. return _this._processIncludesAsync(vertexCode);
  203. })
  204. .then(function (vertexCodeWithIncludes) {
  205. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  206. return _this._loadFragmentShaderAsync(fragmentSource);
  207. })
  208. .then(function (fragmentCode) {
  209. return _this._processIncludesAsync(fragmentCode);
  210. })
  211. .then(function (fragmentCodeWithIncludes) {
  212. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  213. if (baseName) {
  214. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  215. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  216. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  217. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  218. }
  219. else {
  220. _this._vertexSourceCode = finalVertexCode;
  221. _this._fragmentSourceCode = migratedFragmentCode;
  222. }
  223. _this._prepareEffect();
  224. });
  225. }
  226. Object.defineProperty(Effect.prototype, "key", {
  227. /**
  228. * Unique key for this effect
  229. */
  230. get: function () {
  231. return this._key;
  232. },
  233. enumerable: true,
  234. configurable: true
  235. });
  236. /**
  237. * If the effect has been compiled and prepared.
  238. * @returns if the effect is compiled and prepared.
  239. */
  240. Effect.prototype.isReady = function () {
  241. return this._isReady;
  242. };
  243. /**
  244. * The engine the effect was initialized with.
  245. * @returns the engine.
  246. */
  247. Effect.prototype.getEngine = function () {
  248. return this._engine;
  249. };
  250. /**
  251. * The compiled webGL program for the effect
  252. * @returns the webGL program.
  253. */
  254. Effect.prototype.getProgram = function () {
  255. return this._program;
  256. };
  257. /**
  258. * The set of names of attribute variables for the shader.
  259. * @returns An array of attribute names.
  260. */
  261. Effect.prototype.getAttributesNames = function () {
  262. return this._attributesNames;
  263. };
  264. /**
  265. * Returns the attribute at the given index.
  266. * @param index The index of the attribute.
  267. * @returns The location of the attribute.
  268. */
  269. Effect.prototype.getAttributeLocation = function (index) {
  270. return this._attributes[index];
  271. };
  272. /**
  273. * Returns the attribute based on the name of the variable.
  274. * @param name of the attribute to look up.
  275. * @returns the attribute location.
  276. */
  277. Effect.prototype.getAttributeLocationByName = function (name) {
  278. var index = this._attributesNames.indexOf(name);
  279. return this._attributes[index];
  280. };
  281. /**
  282. * The number of attributes.
  283. * @returns the numnber of attributes.
  284. */
  285. Effect.prototype.getAttributesCount = function () {
  286. return this._attributes.length;
  287. };
  288. /**
  289. * Gets the index of a uniform variable.
  290. * @param uniformName of the uniform to look up.
  291. * @returns the index.
  292. */
  293. Effect.prototype.getUniformIndex = function (uniformName) {
  294. return this._uniformsNames.indexOf(uniformName);
  295. };
  296. /**
  297. * Returns the attribute based on the name of the variable.
  298. * @param uniformName of the uniform to look up.
  299. * @returns the location of the uniform.
  300. */
  301. Effect.prototype.getUniform = function (uniformName) {
  302. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  303. };
  304. /**
  305. * Returns an array of sampler variable names
  306. * @returns The array of sampler variable neames.
  307. */
  308. Effect.prototype.getSamplers = function () {
  309. return this._samplers;
  310. };
  311. /**
  312. * The error from the last compilation.
  313. * @returns the error string.
  314. */
  315. Effect.prototype.getCompilationError = function () {
  316. return this._compilationError;
  317. };
  318. /**
  319. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  320. * @param func The callback to be used.
  321. */
  322. Effect.prototype.executeWhenCompiled = function (func) {
  323. if (this.isReady()) {
  324. func(this);
  325. return;
  326. }
  327. this.onCompileObservable.add(function (effect) {
  328. func(effect);
  329. });
  330. };
  331. /** @ignore */
  332. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  333. if (BABYLON.Tools.IsWindowObjectExist()) {
  334. // DOM element ?
  335. if (vertex instanceof HTMLElement) {
  336. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  337. return Promise.resolve(vertexCode);
  338. }
  339. }
  340. // Base64 encoded ?
  341. if (vertex.substr(0, 7) === "base64:") {
  342. var vertexBinary = window.atob(vertex.substr(7));
  343. return Promise.resolve(vertexBinary);
  344. }
  345. // Is in local store ?
  346. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  347. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  348. }
  349. var vertexShaderUrl;
  350. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  351. vertexShaderUrl = vertex;
  352. }
  353. else {
  354. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  355. }
  356. // Vertex shader
  357. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  358. };
  359. /** @ignore */
  360. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  361. if (BABYLON.Tools.IsWindowObjectExist()) {
  362. // DOM element ?
  363. if (fragment instanceof HTMLElement) {
  364. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  365. return Promise.resolve(fragmentCode);
  366. }
  367. }
  368. // Base64 encoded ?
  369. if (fragment.substr(0, 7) === "base64:") {
  370. var fragmentBinary = window.atob(fragment.substr(7));
  371. return Promise.resolve(fragmentBinary);
  372. }
  373. // Is in local store ?
  374. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  375. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  376. }
  377. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  378. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  379. }
  380. var fragmentShaderUrl;
  381. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  382. fragmentShaderUrl = fragment;
  383. }
  384. else {
  385. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  386. }
  387. // Fragment shader
  388. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  389. };
  390. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  391. // Rebuild shaders source code
  392. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  393. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  394. vertexCode = prefix + vertexCode;
  395. fragmentCode = prefix + fragmentCode;
  396. // Number lines of shaders source code
  397. var i = 2;
  398. var regex = /\n/gm;
  399. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  400. i = 2;
  401. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  402. // Dump shaders name and formatted source code
  403. if (this.name.vertexElement) {
  404. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  405. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  406. }
  407. else if (this.name.vertex) {
  408. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  409. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  410. }
  411. else {
  412. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  413. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  414. }
  415. };
  416. ;
  417. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  418. var preparedSourceCode = this._processPrecision(sourceCode);
  419. if (this._engine.webGLVersion == 1) {
  420. return preparedSourceCode;
  421. }
  422. // Already converted
  423. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  424. return preparedSourceCode.replace("#version 300 es", "");
  425. }
  426. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  427. // Remove extensions
  428. // #extension GL_OES_standard_derivatives : enable
  429. // #extension GL_EXT_shader_texture_lod : enable
  430. // #extension GL_EXT_frag_depth : enable
  431. // #extension GL_EXT_draw_buffers : require
  432. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  433. var result = preparedSourceCode.replace(regex, "");
  434. // Migrate to GLSL v300
  435. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  436. result = result.replace(/attribute[ \t]/g, "in ");
  437. result = result.replace(/[ \t]attribute/g, " in");
  438. if (isFragment) {
  439. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  440. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  441. result = result.replace(/texture2D\s*\(/g, "texture(");
  442. result = result.replace(/textureCube\s*\(/g, "texture(");
  443. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  444. result = result.replace(/gl_FragColor/g, "glFragColor");
  445. result = result.replace(/gl_FragData/g, "glFragData");
  446. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  447. }
  448. return result;
  449. };
  450. Effect.prototype._processIncludesAsync = function (sourceCode) {
  451. var _this = this;
  452. return new Promise(function (resolve, reject) {
  453. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  454. var match = regex.exec(sourceCode);
  455. var returnValue = sourceCode;
  456. while (match != null) {
  457. var includeFile = match[1];
  458. // Uniform declaration
  459. if (includeFile.indexOf("__decl__") !== -1) {
  460. includeFile = includeFile.replace(/__decl__/, "");
  461. if (_this._engine.supportsUniformBuffers) {
  462. includeFile = includeFile.replace(/Vertex/, "Ubo");
  463. includeFile = includeFile.replace(/Fragment/, "Ubo");
  464. }
  465. includeFile = includeFile + "Declaration";
  466. }
  467. if (Effect.IncludesShadersStore[includeFile]) {
  468. // Substitution
  469. var includeContent = Effect.IncludesShadersStore[includeFile];
  470. if (match[2]) {
  471. var splits = match[3].split(",");
  472. for (var index = 0; index < splits.length; index += 2) {
  473. var source = new RegExp(splits[index], "g");
  474. var dest = splits[index + 1];
  475. includeContent = includeContent.replace(source, dest);
  476. }
  477. }
  478. if (match[4]) {
  479. var indexString = match[5];
  480. if (indexString.indexOf("..") !== -1) {
  481. var indexSplits = indexString.split("..");
  482. var minIndex = parseInt(indexSplits[0]);
  483. var maxIndex = parseInt(indexSplits[1]);
  484. var sourceIncludeContent = includeContent.slice(0);
  485. includeContent = "";
  486. if (isNaN(maxIndex)) {
  487. maxIndex = _this._indexParameters[indexSplits[1]];
  488. }
  489. for (var i = minIndex; i < maxIndex; i++) {
  490. if (!_this._engine.supportsUniformBuffers) {
  491. // Ubo replacement
  492. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  493. return p1 + "{X}";
  494. });
  495. }
  496. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  497. }
  498. }
  499. else {
  500. if (!_this._engine.supportsUniformBuffers) {
  501. // Ubo replacement
  502. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  503. return p1 + "{X}";
  504. });
  505. }
  506. includeContent = includeContent.replace(/\{X\}/g, indexString);
  507. }
  508. }
  509. // Replace
  510. returnValue = returnValue.replace(match[0], includeContent);
  511. }
  512. else {
  513. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  514. _this._engine._loadFileAsync(includeShaderUrl)
  515. .then(function (fileContent) {
  516. Effect.IncludesShadersStore[includeFile] = fileContent;
  517. return _this._processIncludesAsync(returnValue);
  518. })
  519. .then(function (returnValue) {
  520. resolve(returnValue);
  521. });
  522. return;
  523. }
  524. match = regex.exec(sourceCode);
  525. }
  526. resolve(returnValue);
  527. });
  528. };
  529. Effect.prototype._processPrecision = function (source) {
  530. if (source.indexOf("precision highp float") === -1) {
  531. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  532. source = "precision mediump float;\n" + source;
  533. }
  534. else {
  535. source = "precision highp float;\n" + source;
  536. }
  537. }
  538. else {
  539. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  540. source = source.replace("precision highp float", "precision mediump float");
  541. }
  542. }
  543. return source;
  544. };
  545. /**
  546. * Recompiles the webGL program
  547. * @param vertexSourceCode The source code for the vertex shader.
  548. * @param fragmentSourceCode The source code for the fragment shader.
  549. * @param onCompiled Callback called when completed.
  550. * @param onError Callback called on error.
  551. */
  552. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  553. var _this = this;
  554. this._isReady = false;
  555. this._vertexSourceCodeOverride = vertexSourceCode;
  556. this._fragmentSourceCodeOverride = fragmentSourceCode;
  557. this.onError = function (effect, error) {
  558. if (onError) {
  559. onError(error);
  560. }
  561. };
  562. this.onCompiled = function () {
  563. var scenes = _this.getEngine().scenes;
  564. for (var i = 0; i < scenes.length; i++) {
  565. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  566. }
  567. if (onCompiled) {
  568. onCompiled(_this._program);
  569. }
  570. };
  571. this._fallbacks = null;
  572. this._prepareEffect();
  573. };
  574. /**
  575. * Gets the uniform locations of the the specified variable names
  576. * @param names THe names of the variables to lookup.
  577. * @returns Array of locations in the same order as variable names.
  578. */
  579. Effect.prototype.getSpecificUniformLocations = function (names) {
  580. var engine = this._engine;
  581. return engine.getUniforms(this._program, names);
  582. };
  583. /**
  584. * Prepares the effect
  585. */
  586. Effect.prototype._prepareEffect = function () {
  587. var attributesNames = this._attributesNames;
  588. var defines = this.defines;
  589. var fallbacks = this._fallbacks;
  590. this._valueCache = {};
  591. var previousProgram = this._program;
  592. try {
  593. var engine = this._engine;
  594. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  595. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  596. }
  597. else {
  598. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  599. }
  600. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  601. if (engine.supportsUniformBuffers) {
  602. for (var name in this._uniformBuffersNames) {
  603. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  604. }
  605. }
  606. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  607. this._attributes = engine.getAttributes(this._program, attributesNames);
  608. var index;
  609. for (index = 0; index < this._samplers.length; index++) {
  610. var sampler = this.getUniform(this._samplers[index]);
  611. if (sampler == null) {
  612. this._samplers.splice(index, 1);
  613. index--;
  614. }
  615. }
  616. engine.bindSamplers(this);
  617. this._compilationError = "";
  618. this._isReady = true;
  619. if (this.onCompiled) {
  620. this.onCompiled(this);
  621. }
  622. this.onCompileObservable.notifyObservers(this);
  623. this.onCompileObservable.clear();
  624. // Unbind mesh reference in fallbacks
  625. if (this._fallbacks) {
  626. this._fallbacks.unBindMesh();
  627. }
  628. if (previousProgram) {
  629. this.getEngine()._deleteProgram(previousProgram);
  630. }
  631. }
  632. catch (e) {
  633. this._compilationError = e.message;
  634. // Let's go through fallbacks then
  635. BABYLON.Tools.Error("Unable to compile effect:");
  636. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  637. return " " + uniform;
  638. }));
  639. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  640. return " " + attribute;
  641. }));
  642. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  643. BABYLON.Tools.Error("Error: " + this._compilationError);
  644. if (previousProgram) {
  645. this._program = previousProgram;
  646. this._isReady = true;
  647. if (this.onError) {
  648. this.onError(this, this._compilationError);
  649. }
  650. this.onErrorObservable.notifyObservers(this);
  651. }
  652. if (fallbacks && fallbacks.isMoreFallbacks) {
  653. BABYLON.Tools.Error("Trying next fallback.");
  654. this.defines = fallbacks.reduce(this.defines);
  655. this._prepareEffect();
  656. }
  657. else {
  658. if (this.onError) {
  659. this.onError(this, this._compilationError);
  660. }
  661. this.onErrorObservable.notifyObservers(this);
  662. this.onErrorObservable.clear();
  663. // Unbind mesh reference in fallbacks
  664. if (this._fallbacks) {
  665. this._fallbacks.unBindMesh();
  666. }
  667. }
  668. }
  669. };
  670. Object.defineProperty(Effect.prototype, "isSupported", {
  671. /**
  672. * Checks if the effect is supported. (Must be called after compilation)
  673. */
  674. get: function () {
  675. return this._compilationError === "";
  676. },
  677. enumerable: true,
  678. configurable: true
  679. });
  680. /**
  681. * Binds a texture to the engine to be used as output of the shader.
  682. * @param channel Name of the output variable.
  683. * @param texture Texture to bind.
  684. */
  685. Effect.prototype._bindTexture = function (channel, texture) {
  686. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  687. };
  688. /**
  689. * Sets a texture on the engine to be used in the shader.
  690. * @param channel Name of the sampler variable.
  691. * @param texture Texture to set.
  692. */
  693. Effect.prototype.setTexture = function (channel, texture) {
  694. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  695. };
  696. /**
  697. * Sets an array of textures on the engine to be used in the shader.
  698. * @param channel Name of the variable.
  699. * @param textures Textures to set.
  700. */
  701. Effect.prototype.setTextureArray = function (channel, textures) {
  702. if (this._samplers.indexOf(channel + "Ex") === -1) {
  703. var initialPos = this._samplers.indexOf(channel);
  704. for (var index = 1; index < textures.length; index++) {
  705. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  706. }
  707. }
  708. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  709. };
  710. /**
  711. * 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)
  712. * @param channel Name of the sampler variable.
  713. * @param postProcess Post process to get the input texture from.
  714. */
  715. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  716. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  717. };
  718. /** @ignore */
  719. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  720. var cache = this._valueCache[uniformName];
  721. var flag = matrix.updateFlag;
  722. if (cache !== undefined && cache === flag) {
  723. return false;
  724. }
  725. this._valueCache[uniformName] = flag;
  726. return true;
  727. };
  728. /** @ignore */
  729. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  730. var cache = this._valueCache[uniformName];
  731. if (!cache) {
  732. cache = [x, y];
  733. this._valueCache[uniformName] = cache;
  734. return true;
  735. }
  736. var changed = false;
  737. if (cache[0] !== x) {
  738. cache[0] = x;
  739. changed = true;
  740. }
  741. if (cache[1] !== y) {
  742. cache[1] = y;
  743. changed = true;
  744. }
  745. return changed;
  746. };
  747. /** @ignore */
  748. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  749. var cache = this._valueCache[uniformName];
  750. if (!cache) {
  751. cache = [x, y, z];
  752. this._valueCache[uniformName] = cache;
  753. return true;
  754. }
  755. var changed = false;
  756. if (cache[0] !== x) {
  757. cache[0] = x;
  758. changed = true;
  759. }
  760. if (cache[1] !== y) {
  761. cache[1] = y;
  762. changed = true;
  763. }
  764. if (cache[2] !== z) {
  765. cache[2] = z;
  766. changed = true;
  767. }
  768. return changed;
  769. };
  770. /** @ignore */
  771. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  772. var cache = this._valueCache[uniformName];
  773. if (!cache) {
  774. cache = [x, y, z, w];
  775. this._valueCache[uniformName] = cache;
  776. return true;
  777. }
  778. var changed = false;
  779. if (cache[0] !== x) {
  780. cache[0] = x;
  781. changed = true;
  782. }
  783. if (cache[1] !== y) {
  784. cache[1] = y;
  785. changed = true;
  786. }
  787. if (cache[2] !== z) {
  788. cache[2] = z;
  789. changed = true;
  790. }
  791. if (cache[3] !== w) {
  792. cache[3] = w;
  793. changed = true;
  794. }
  795. return changed;
  796. };
  797. /**
  798. * Binds a buffer to a uniform.
  799. * @param buffer Buffer to bind.
  800. * @param name Name of the uniform variable to bind to.
  801. */
  802. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  803. var bufferName = this._uniformBuffersNames[name];
  804. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  805. return;
  806. }
  807. Effect._baseCache[bufferName] = buffer;
  808. this._engine.bindUniformBufferBase(buffer, bufferName);
  809. };
  810. /**
  811. * Binds block to a uniform.
  812. * @param blockName Name of the block to bind.
  813. * @param index Index to bind.
  814. */
  815. Effect.prototype.bindUniformBlock = function (blockName, index) {
  816. this._engine.bindUniformBlock(this._program, blockName, index);
  817. };
  818. /**
  819. * Sets an interger value on a uniform variable.
  820. * @param uniformName Name of the variable.
  821. * @param value Value to be set.
  822. * @returns this effect.
  823. */
  824. Effect.prototype.setInt = function (uniformName, value) {
  825. var cache = this._valueCache[uniformName];
  826. if (cache !== undefined && cache === value)
  827. return this;
  828. this._valueCache[uniformName] = value;
  829. this._engine.setInt(this.getUniform(uniformName), value);
  830. return this;
  831. };
  832. /**
  833. * Sets an int array on a uniform variable.
  834. * @param uniformName Name of the variable.
  835. * @param array array to be set.
  836. * @returns this effect.
  837. */
  838. Effect.prototype.setIntArray = function (uniformName, array) {
  839. this._valueCache[uniformName] = null;
  840. this._engine.setIntArray(this.getUniform(uniformName), array);
  841. return this;
  842. };
  843. /**
  844. * 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)
  845. * @param uniformName Name of the variable.
  846. * @param array array to be set.
  847. * @returns this effect.
  848. */
  849. Effect.prototype.setIntArray2 = function (uniformName, array) {
  850. this._valueCache[uniformName] = null;
  851. this._engine.setIntArray2(this.getUniform(uniformName), array);
  852. return this;
  853. };
  854. /**
  855. * 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)
  856. * @param uniformName Name of the variable.
  857. * @param array array to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setIntArray3 = function (uniformName, array) {
  861. this._valueCache[uniformName] = null;
  862. this._engine.setIntArray3(this.getUniform(uniformName), array);
  863. return this;
  864. };
  865. /**
  866. * 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)
  867. * @param uniformName Name of the variable.
  868. * @param array array to be set.
  869. * @returns this effect.
  870. */
  871. Effect.prototype.setIntArray4 = function (uniformName, array) {
  872. this._valueCache[uniformName] = null;
  873. this._engine.setIntArray4(this.getUniform(uniformName), array);
  874. return this;
  875. };
  876. /**
  877. * Sets an float array on a uniform variable.
  878. * @param uniformName Name of the variable.
  879. * @param array array to be set.
  880. * @returns this effect.
  881. */
  882. Effect.prototype.setFloatArray = function (uniformName, array) {
  883. this._valueCache[uniformName] = null;
  884. this._engine.setFloatArray(this.getUniform(uniformName), array);
  885. return this;
  886. };
  887. /**
  888. * 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)
  889. * @param uniformName Name of the variable.
  890. * @param array array to be set.
  891. * @returns this effect.
  892. */
  893. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  894. this._valueCache[uniformName] = null;
  895. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  896. return this;
  897. };
  898. /**
  899. * 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)
  900. * @param uniformName Name of the variable.
  901. * @param array array to be set.
  902. * @returns this effect.
  903. */
  904. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  905. this._valueCache[uniformName] = null;
  906. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  907. return this;
  908. };
  909. /**
  910. * 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)
  911. * @param uniformName Name of the variable.
  912. * @param array array to be set.
  913. * @returns this effect.
  914. */
  915. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  916. this._valueCache[uniformName] = null;
  917. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  918. return this;
  919. };
  920. /**
  921. * Sets an array on a uniform variable.
  922. * @param uniformName Name of the variable.
  923. * @param array array to be set.
  924. * @returns this effect.
  925. */
  926. Effect.prototype.setArray = function (uniformName, array) {
  927. this._valueCache[uniformName] = null;
  928. this._engine.setArray(this.getUniform(uniformName), array);
  929. return this;
  930. };
  931. /**
  932. * 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)
  933. * @param uniformName Name of the variable.
  934. * @param array array to be set.
  935. * @returns this effect.
  936. */
  937. Effect.prototype.setArray2 = function (uniformName, array) {
  938. this._valueCache[uniformName] = null;
  939. this._engine.setArray2(this.getUniform(uniformName), array);
  940. return this;
  941. };
  942. /**
  943. * 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)
  944. * @param uniformName Name of the variable.
  945. * @param array array to be set.
  946. * @returns this effect.
  947. */
  948. Effect.prototype.setArray3 = function (uniformName, array) {
  949. this._valueCache[uniformName] = null;
  950. this._engine.setArray3(this.getUniform(uniformName), array);
  951. return this;
  952. };
  953. /**
  954. * 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)
  955. * @param uniformName Name of the variable.
  956. * @param array array to be set.
  957. * @returns this effect.
  958. */
  959. Effect.prototype.setArray4 = function (uniformName, array) {
  960. this._valueCache[uniformName] = null;
  961. this._engine.setArray4(this.getUniform(uniformName), array);
  962. return this;
  963. };
  964. /**
  965. * Sets matrices on a uniform variable.
  966. * @param uniformName Name of the variable.
  967. * @param matrices matrices to be set.
  968. * @returns this effect.
  969. */
  970. Effect.prototype.setMatrices = function (uniformName, matrices) {
  971. if (!matrices) {
  972. return this;
  973. }
  974. this._valueCache[uniformName] = null;
  975. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  976. return this;
  977. };
  978. /**
  979. * Sets matrix on a uniform variable.
  980. * @param uniformName Name of the variable.
  981. * @param matrix matrix to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setMatrix = function (uniformName, matrix) {
  985. if (this._cacheMatrix(uniformName, matrix)) {
  986. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  987. }
  988. return this;
  989. };
  990. /**
  991. * 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)
  992. * @param uniformName Name of the variable.
  993. * @param matrix matrix to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  999. return this;
  1000. };
  1001. /**
  1002. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1003. * @param uniformName Name of the variable.
  1004. * @param matrix matrix to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets a float on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param value value to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setFloat = function (uniformName, value) {
  1019. var cache = this._valueCache[uniformName];
  1020. if (cache !== undefined && cache === value)
  1021. return this;
  1022. this._valueCache[uniformName] = value;
  1023. this._engine.setFloat(this.getUniform(uniformName), value);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a boolean on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param bool value to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setBool = function (uniformName, bool) {
  1033. var cache = this._valueCache[uniformName];
  1034. if (cache !== undefined && cache === bool)
  1035. return this;
  1036. this._valueCache[uniformName] = bool;
  1037. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1038. return this;
  1039. };
  1040. /**
  1041. * Sets a Vector2 on a uniform variable.
  1042. * @param uniformName Name of the variable.
  1043. * @param vector2 vector2 to be set.
  1044. * @returns this effect.
  1045. */
  1046. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1047. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1048. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1049. }
  1050. return this;
  1051. };
  1052. /**
  1053. * Sets a float2 on a uniform variable.
  1054. * @param uniformName Name of the variable.
  1055. * @param x First float in float2.
  1056. * @param y Second float in float2.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1060. if (this._cacheFloat2(uniformName, x, y)) {
  1061. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a Vector3 on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param vector3 Value to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1072. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1073. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1074. }
  1075. return this;
  1076. };
  1077. /**
  1078. * Sets a float3 on a uniform variable.
  1079. * @param uniformName Name of the variable.
  1080. * @param x First float in float3.
  1081. * @param y Second float in float3.
  1082. * @param z Third float in float3.
  1083. * @returns this effect.
  1084. */
  1085. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1086. if (this._cacheFloat3(uniformName, x, y, z)) {
  1087. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1088. }
  1089. return this;
  1090. };
  1091. /**
  1092. * Sets a Vector4 on a uniform variable.
  1093. * @param uniformName Name of the variable.
  1094. * @param vector4 Value to be set.
  1095. * @returns this effect.
  1096. */
  1097. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1098. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1099. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1100. }
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a float4 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param x First float in float4.
  1107. * @param y Second float in float4.
  1108. * @param z Third float in float4.
  1109. * @param w Fourth float in float4.
  1110. * @returns this effect.
  1111. */
  1112. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1113. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1114. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1115. }
  1116. return this;
  1117. };
  1118. /**
  1119. * Sets a Color3 on a uniform variable.
  1120. * @param uniformName Name of the variable.
  1121. * @param color3 Value to be set.
  1122. * @returns this effect.
  1123. */
  1124. Effect.prototype.setColor3 = function (uniformName, color3) {
  1125. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1126. this._engine.setColor3(this.getUniform(uniformName), color3);
  1127. }
  1128. return this;
  1129. };
  1130. /**
  1131. * Sets a Color4 on a uniform variable.
  1132. * @param uniformName Name of the variable.
  1133. * @param color3 Value to be set.
  1134. * @param alpha Alpha value to be set.
  1135. * @returns this effect.
  1136. */
  1137. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1138. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1139. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1140. }
  1141. return this;
  1142. };
  1143. /**
  1144. * Resets the cache of effects.
  1145. */
  1146. Effect.ResetCache = function () {
  1147. Effect._baseCache = {};
  1148. };
  1149. Effect._uniqueIdSeed = 0;
  1150. Effect._baseCache = {};
  1151. // Statics
  1152. /**
  1153. * Store of each shader (The can be looked up using effect.key)
  1154. */
  1155. Effect.ShadersStore = {};
  1156. /**
  1157. * Store of each included file for a shader (The can be looked up using effect.key)
  1158. */
  1159. Effect.IncludesShadersStore = {};
  1160. return Effect;
  1161. }());
  1162. BABYLON.Effect = Effect;
  1163. })(BABYLON || (BABYLON = {}));
  1164. //# sourceMappingURL=babylon.effect.js.map
  1165. //# sourceMappingURL=babylon.types.js.map
  1166. var BABYLON;
  1167. (function (BABYLON) {
  1168. var KeyboardEventTypes = /** @class */ (function () {
  1169. function KeyboardEventTypes() {
  1170. }
  1171. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1172. get: function () {
  1173. return KeyboardEventTypes._KEYDOWN;
  1174. },
  1175. enumerable: true,
  1176. configurable: true
  1177. });
  1178. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1179. get: function () {
  1180. return KeyboardEventTypes._KEYUP;
  1181. },
  1182. enumerable: true,
  1183. configurable: true
  1184. });
  1185. KeyboardEventTypes._KEYDOWN = 0x01;
  1186. KeyboardEventTypes._KEYUP = 0x02;
  1187. return KeyboardEventTypes;
  1188. }());
  1189. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1190. var KeyboardInfo = /** @class */ (function () {
  1191. function KeyboardInfo(type, event) {
  1192. this.type = type;
  1193. this.event = event;
  1194. }
  1195. return KeyboardInfo;
  1196. }());
  1197. BABYLON.KeyboardInfo = KeyboardInfo;
  1198. /**
  1199. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1200. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1201. */
  1202. var KeyboardInfoPre = /** @class */ (function (_super) {
  1203. __extends(KeyboardInfoPre, _super);
  1204. function KeyboardInfoPre(type, event) {
  1205. var _this = _super.call(this, type, event) || this;
  1206. _this.skipOnPointerObservable = false;
  1207. return _this;
  1208. }
  1209. return KeyboardInfoPre;
  1210. }(KeyboardInfo));
  1211. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1212. })(BABYLON || (BABYLON = {}));
  1213. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1214. var BABYLON;
  1215. (function (BABYLON) {
  1216. var PointerEventTypes = /** @class */ (function () {
  1217. function PointerEventTypes() {
  1218. }
  1219. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1220. get: function () {
  1221. return PointerEventTypes._POINTERDOWN;
  1222. },
  1223. enumerable: true,
  1224. configurable: true
  1225. });
  1226. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1227. get: function () {
  1228. return PointerEventTypes._POINTERUP;
  1229. },
  1230. enumerable: true,
  1231. configurable: true
  1232. });
  1233. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1234. get: function () {
  1235. return PointerEventTypes._POINTERMOVE;
  1236. },
  1237. enumerable: true,
  1238. configurable: true
  1239. });
  1240. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1241. get: function () {
  1242. return PointerEventTypes._POINTERWHEEL;
  1243. },
  1244. enumerable: true,
  1245. configurable: true
  1246. });
  1247. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1248. get: function () {
  1249. return PointerEventTypes._POINTERPICK;
  1250. },
  1251. enumerable: true,
  1252. configurable: true
  1253. });
  1254. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1255. get: function () {
  1256. return PointerEventTypes._POINTERTAP;
  1257. },
  1258. enumerable: true,
  1259. configurable: true
  1260. });
  1261. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERDOUBLETAP;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. PointerEventTypes._POINTERDOWN = 0x01;
  1269. PointerEventTypes._POINTERUP = 0x02;
  1270. PointerEventTypes._POINTERMOVE = 0x04;
  1271. PointerEventTypes._POINTERWHEEL = 0x08;
  1272. PointerEventTypes._POINTERPICK = 0x10;
  1273. PointerEventTypes._POINTERTAP = 0x20;
  1274. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1275. return PointerEventTypes;
  1276. }());
  1277. BABYLON.PointerEventTypes = PointerEventTypes;
  1278. var PointerInfoBase = /** @class */ (function () {
  1279. function PointerInfoBase(type, event) {
  1280. this.type = type;
  1281. this.event = event;
  1282. }
  1283. return PointerInfoBase;
  1284. }());
  1285. BABYLON.PointerInfoBase = PointerInfoBase;
  1286. /**
  1287. * This class is used to store pointer related info for the onPrePointerObservable event.
  1288. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1289. */
  1290. var PointerInfoPre = /** @class */ (function (_super) {
  1291. __extends(PointerInfoPre, _super);
  1292. function PointerInfoPre(type, event, localX, localY) {
  1293. var _this = _super.call(this, type, event) || this;
  1294. _this.skipOnPointerObservable = false;
  1295. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1296. return _this;
  1297. }
  1298. return PointerInfoPre;
  1299. }(PointerInfoBase));
  1300. BABYLON.PointerInfoPre = PointerInfoPre;
  1301. /**
  1302. * This type contains all the data related to a pointer event in Babylon.js.
  1303. * 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.
  1304. */
  1305. var PointerInfo = /** @class */ (function (_super) {
  1306. __extends(PointerInfo, _super);
  1307. function PointerInfo(type, event, pickInfo) {
  1308. var _this = _super.call(this, type, event) || this;
  1309. _this.pickInfo = pickInfo;
  1310. return _this;
  1311. }
  1312. return PointerInfo;
  1313. }(PointerInfoBase));
  1314. BABYLON.PointerInfo = PointerInfo;
  1315. })(BABYLON || (BABYLON = {}));
  1316. //# sourceMappingURL=babylon.pointerEvents.js.map
  1317. var BABYLON;
  1318. (function (BABYLON) {
  1319. BABYLON.ToGammaSpace = 1 / 2.2;
  1320. BABYLON.ToLinearSpace = 2.2;
  1321. BABYLON.Epsilon = 0.001;
  1322. /**
  1323. * Class used to hold a RBG color
  1324. */
  1325. var Color3 = /** @class */ (function () {
  1326. /**
  1327. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1328. * @param r defines the red component (between 0 and 1, default is 0)
  1329. * @param g defines the green component (between 0 and 1, default is 0)
  1330. * @param b defines the blue component (between 0 and 1, default is 0)
  1331. */
  1332. function Color3(
  1333. /**
  1334. * Defines the red component (between 0 and 1, default is 0)
  1335. */
  1336. r,
  1337. /**
  1338. * Defines the green component (between 0 and 1, default is 0)
  1339. */
  1340. g,
  1341. /**
  1342. * Defines the blue component (between 0 and 1, default is 0)
  1343. */
  1344. b) {
  1345. if (r === void 0) { r = 0; }
  1346. if (g === void 0) { g = 0; }
  1347. if (b === void 0) { b = 0; }
  1348. this.r = r;
  1349. this.g = g;
  1350. this.b = b;
  1351. }
  1352. /**
  1353. * Creates a string with the Color3 current values
  1354. * @returns the string representation of the Color3 object
  1355. */
  1356. Color3.prototype.toString = function () {
  1357. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1358. };
  1359. /**
  1360. * Returns the string "Color3"
  1361. * @returns "Color3"
  1362. */
  1363. Color3.prototype.getClassName = function () {
  1364. return "Color3";
  1365. };
  1366. /**
  1367. * Compute the Color3 hash code
  1368. * @returns an unique number that can be used to hash Color3 objects
  1369. */
  1370. Color3.prototype.getHashCode = function () {
  1371. var hash = this.r || 0;
  1372. hash = (hash * 397) ^ (this.g || 0);
  1373. hash = (hash * 397) ^ (this.b || 0);
  1374. return hash;
  1375. };
  1376. // Operators
  1377. /**
  1378. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1379. * @param array defines the array where to store the r,g,b components
  1380. * @param index defines an optional index in the target array to define where to start storing values
  1381. * @returns the current Color3 object
  1382. */
  1383. Color3.prototype.toArray = function (array, index) {
  1384. if (index === undefined) {
  1385. index = 0;
  1386. }
  1387. array[index] = this.r;
  1388. array[index + 1] = this.g;
  1389. array[index + 2] = this.b;
  1390. return this;
  1391. };
  1392. /**
  1393. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1394. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1395. * @returns a new {BABYLON.Color4} object
  1396. */
  1397. Color3.prototype.toColor4 = function (alpha) {
  1398. if (alpha === void 0) { alpha = 1; }
  1399. return new Color4(this.r, this.g, this.b, alpha);
  1400. };
  1401. /**
  1402. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1403. * @returns the new array
  1404. */
  1405. Color3.prototype.asArray = function () {
  1406. var result = new Array();
  1407. this.toArray(result, 0);
  1408. return result;
  1409. };
  1410. /**
  1411. * Returns the luminance value
  1412. * @returns a float value
  1413. */
  1414. Color3.prototype.toLuminance = function () {
  1415. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1416. };
  1417. /**
  1418. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1419. * @param otherColor defines the second operand
  1420. * @returns the new Color3 object
  1421. */
  1422. Color3.prototype.multiply = function (otherColor) {
  1423. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1424. };
  1425. /**
  1426. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1427. * @param otherColor defines the second operand
  1428. * @param result defines the Color3 object where to store the result
  1429. * @returns the current Color3
  1430. */
  1431. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1432. result.r = this.r * otherColor.r;
  1433. result.g = this.g * otherColor.g;
  1434. result.b = this.b * otherColor.b;
  1435. return this;
  1436. };
  1437. /**
  1438. * Determines equality between Color3 objects
  1439. * @param otherColor defines the second operand
  1440. * @returns true if the rgb values are equal to the passed ones
  1441. */
  1442. Color3.prototype.equals = function (otherColor) {
  1443. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1444. };
  1445. /**
  1446. * Determines equality between the current Color3 object and a set of r,b,g values
  1447. * @param r defines the red component to check
  1448. * @param g defines the green component to check
  1449. * @param b defines the blue component to check
  1450. * @returns true if the rgb values are equal to the passed ones
  1451. */
  1452. Color3.prototype.equalsFloats = function (r, g, b) {
  1453. return this.r === r && this.g === g && this.b === b;
  1454. };
  1455. /**
  1456. * Multiplies in place each rgb value by scale
  1457. * @param scale defines the scaling factor
  1458. * @returns the updated Color3.
  1459. */
  1460. Color3.prototype.scale = function (scale) {
  1461. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1462. };
  1463. /**
  1464. * Multiplies the rgb values by scale and stores the result into "result"
  1465. * @param scale defines the scaling factor
  1466. * @param result defines the Color3 object where to store the result
  1467. * @returns the unmodified current Color3.
  1468. */
  1469. Color3.prototype.scaleToRef = function (scale, result) {
  1470. result.r = this.r * scale;
  1471. result.g = this.g * scale;
  1472. result.b = this.b * scale;
  1473. return this;
  1474. };
  1475. /**
  1476. * Clamps the rgb values by the min and max values and stores the result into "result"
  1477. * @param min defines minimum clamping value (default is 0)
  1478. * @param max defines maximum clamping value (default is 1)
  1479. * @param result defines color to store the result into
  1480. * @returns the original Color3
  1481. */
  1482. Color3.prototype.clampToRef = function (min, max, result) {
  1483. if (min === void 0) { min = 0; }
  1484. if (max === void 0) { max = 1; }
  1485. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1486. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1487. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1488. return this;
  1489. };
  1490. /**
  1491. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1492. * @param otherColor defines the second operand
  1493. * @returns the new Color3
  1494. */
  1495. Color3.prototype.add = function (otherColor) {
  1496. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1497. };
  1498. /**
  1499. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1500. * @param otherColor defines the second operand
  1501. * @param result defines Color3 object to store the result into
  1502. * @returns the unmodified current Color3
  1503. */
  1504. Color3.prototype.addToRef = function (otherColor, result) {
  1505. result.r = this.r + otherColor.r;
  1506. result.g = this.g + otherColor.g;
  1507. result.b = this.b + otherColor.b;
  1508. return this;
  1509. };
  1510. /**
  1511. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1512. * @param otherColor defines the second operand
  1513. * @returns the new Color3
  1514. */
  1515. Color3.prototype.subtract = function (otherColor) {
  1516. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1517. };
  1518. /**
  1519. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1520. * @param otherColor defines the second operand
  1521. * @param result defines Color3 object to store the result into
  1522. * @returns the unmodified current Color3
  1523. */
  1524. Color3.prototype.subtractToRef = function (otherColor, result) {
  1525. result.r = this.r - otherColor.r;
  1526. result.g = this.g - otherColor.g;
  1527. result.b = this.b - otherColor.b;
  1528. return this;
  1529. };
  1530. /**
  1531. * Copy the current object
  1532. * @returns a new Color3 copied the current one
  1533. */
  1534. Color3.prototype.clone = function () {
  1535. return new Color3(this.r, this.g, this.b);
  1536. };
  1537. /**
  1538. * Copies the rgb values from the source in the current Color3
  1539. * @param source defines the source Color3 object
  1540. * @returns the updated Color3 object
  1541. */
  1542. Color3.prototype.copyFrom = function (source) {
  1543. this.r = source.r;
  1544. this.g = source.g;
  1545. this.b = source.b;
  1546. return this;
  1547. };
  1548. /**
  1549. * Updates the Color3 rgb values from the passed floats
  1550. * @param r defines the red component to read from
  1551. * @param g defines the green component to read from
  1552. * @param b defines the blue component to read from
  1553. * @returns the current Color3 object
  1554. */
  1555. Color3.prototype.copyFromFloats = function (r, g, b) {
  1556. this.r = r;
  1557. this.g = g;
  1558. this.b = b;
  1559. return this;
  1560. };
  1561. /**
  1562. * Updates the Color3 rgb values from the passed floats
  1563. * @param r defines the red component to read from
  1564. * @param g defines the green component to read from
  1565. * @param b defines the blue component to read from
  1566. * @returns the current Color3 object
  1567. */
  1568. Color3.prototype.set = function (r, g, b) {
  1569. return this.copyFromFloats(r, g, b);
  1570. };
  1571. /**
  1572. * Compute the Color3 hexadecimal code as a string
  1573. * @returns a string containing the hexadecimal representation of the Color3 object
  1574. */
  1575. Color3.prototype.toHexString = function () {
  1576. var intR = (this.r * 255) | 0;
  1577. var intG = (this.g * 255) | 0;
  1578. var intB = (this.b * 255) | 0;
  1579. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1580. };
  1581. /**
  1582. * Computes a new Color3 converted from the current one to linear space
  1583. * @returns a new Color3 object
  1584. */
  1585. Color3.prototype.toLinearSpace = function () {
  1586. var convertedColor = new Color3();
  1587. this.toLinearSpaceToRef(convertedColor);
  1588. return convertedColor;
  1589. };
  1590. /**
  1591. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1592. * @param convertedColor defines the Color3 object where to store the linear space version
  1593. * @returns the unmodified Color3
  1594. */
  1595. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1596. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1597. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1598. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1599. return this;
  1600. };
  1601. /**
  1602. * Computes a new Color3 converted from the current one to gamma space
  1603. * @returns a new Color3 object
  1604. */
  1605. Color3.prototype.toGammaSpace = function () {
  1606. var convertedColor = new Color3();
  1607. this.toGammaSpaceToRef(convertedColor);
  1608. return convertedColor;
  1609. };
  1610. /**
  1611. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1612. * @param convertedColor defines the Color3 object where to store the gamma space version
  1613. * @returns the unmodified Color3
  1614. */
  1615. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1616. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1617. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1618. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1619. return this;
  1620. };
  1621. // Statics
  1622. /**
  1623. * Creates a new Color3 from the string containing valid hexadecimal values
  1624. * @param hex defines a string containing valid hexadecimal values
  1625. * @returns a new Color3 object
  1626. */
  1627. Color3.FromHexString = function (hex) {
  1628. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1629. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1630. return new Color3(0, 0, 0);
  1631. }
  1632. var r = parseInt(hex.substring(1, 3), 16);
  1633. var g = parseInt(hex.substring(3, 5), 16);
  1634. var b = parseInt(hex.substring(5, 7), 16);
  1635. return Color3.FromInts(r, g, b);
  1636. };
  1637. /**
  1638. * Creates a new Vector3 from the starting index of the passed array
  1639. * @param array defines the source array
  1640. * @param offset defines an offset in the source array
  1641. * @returns a new Color3 object
  1642. */
  1643. Color3.FromArray = function (array, offset) {
  1644. if (offset === void 0) { offset = 0; }
  1645. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1646. };
  1647. /**
  1648. * Creates a new Color3 from integer values (< 256)
  1649. * @param r defines the red component to read from (value between 0 and 255)
  1650. * @param g defines the green component to read from (value between 0 and 255)
  1651. * @param b defines the blue component to read from (value between 0 and 255)
  1652. * @returns a new Color3 object
  1653. */
  1654. Color3.FromInts = function (r, g, b) {
  1655. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1656. };
  1657. /**
  1658. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1659. * @param start defines the start Color3 value
  1660. * @param end defines the end Color3 value
  1661. * @param amount defines the gradient value between start and end
  1662. * @returns a new Color3 object
  1663. */
  1664. Color3.Lerp = function (start, end, amount) {
  1665. var r = start.r + ((end.r - start.r) * amount);
  1666. var g = start.g + ((end.g - start.g) * amount);
  1667. var b = start.b + ((end.b - start.b) * amount);
  1668. return new Color3(r, g, b);
  1669. };
  1670. /**
  1671. * Returns a Color3 value containing a red color
  1672. * @returns a new Color3 object
  1673. */
  1674. Color3.Red = function () { return new Color3(1, 0, 0); };
  1675. /**
  1676. * Returns a Color3 value containing a green color
  1677. * @returns a new Color3 object
  1678. */
  1679. Color3.Green = function () { return new Color3(0, 1, 0); };
  1680. /**
  1681. * Returns a Color3 value containing a blue color
  1682. * @returns a new Color3 object
  1683. */
  1684. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1685. /**
  1686. * Returns a Color3 value containing a black color
  1687. * @returns a new Color3 object
  1688. */
  1689. Color3.Black = function () { return new Color3(0, 0, 0); };
  1690. /**
  1691. * Returns a Color3 value containing a white color
  1692. * @returns a new Color3 object
  1693. */
  1694. Color3.White = function () { return new Color3(1, 1, 1); };
  1695. /**
  1696. * Returns a Color3 value containing a purple color
  1697. * @returns a new Color3 object
  1698. */
  1699. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1700. /**
  1701. * Returns a Color3 value containing a magenta color
  1702. * @returns a new Color3 object
  1703. */
  1704. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1705. /**
  1706. * Returns a Color3 value containing a yellow color
  1707. * @returns a new Color3 object
  1708. */
  1709. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1710. /**
  1711. * Returns a Color3 value containing a gray color
  1712. * @returns a new Color3 object
  1713. */
  1714. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1715. /**
  1716. * Returns a Color3 value containing a teal color
  1717. * @returns a new Color3 object
  1718. */
  1719. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1720. /**
  1721. * Returns a Color3 value containing a random color
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1725. return Color3;
  1726. }());
  1727. BABYLON.Color3 = Color3;
  1728. /**
  1729. * Class used to hold a RBGA color
  1730. */
  1731. var Color4 = /** @class */ (function () {
  1732. /**
  1733. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1734. * @param r defines the red component (between 0 and 1, default is 0)
  1735. * @param g defines the green component (between 0 and 1, default is 0)
  1736. * @param b defines the blue component (between 0 and 1, default is 0)
  1737. * @param a defines the alpha component (between 0 and 1, default is 1)
  1738. */
  1739. function Color4(
  1740. /**
  1741. * Defines the red component (between 0 and 1, default is 0)
  1742. */
  1743. r,
  1744. /**
  1745. * Defines the green component (between 0 and 1, default is 0)
  1746. */
  1747. g,
  1748. /**
  1749. * Defines the blue component (between 0 and 1, default is 0)
  1750. */
  1751. b,
  1752. /**
  1753. * Defines the alpha component (between 0 and 1, default is 1)
  1754. */
  1755. a) {
  1756. if (r === void 0) { r = 0; }
  1757. if (g === void 0) { g = 0; }
  1758. if (b === void 0) { b = 0; }
  1759. if (a === void 0) { a = 1; }
  1760. this.r = r;
  1761. this.g = g;
  1762. this.b = b;
  1763. this.a = a;
  1764. }
  1765. // Operators
  1766. /**
  1767. * Adds in place the passed Color4 values to the current Color4 object
  1768. * @param right defines the second operand
  1769. * @returns the current updated Color4 object
  1770. */
  1771. Color4.prototype.addInPlace = function (right) {
  1772. this.r += right.r;
  1773. this.g += right.g;
  1774. this.b += right.b;
  1775. this.a += right.a;
  1776. return this;
  1777. };
  1778. /**
  1779. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1780. * @returns the new array
  1781. */
  1782. Color4.prototype.asArray = function () {
  1783. var result = new Array();
  1784. this.toArray(result, 0);
  1785. return result;
  1786. };
  1787. /**
  1788. * Stores from the starting index in the passed array the Color4 successive values
  1789. * @param array defines the array where to store the r,g,b components
  1790. * @param index defines an optional index in the target array to define where to start storing values
  1791. * @returns the current Color4 object
  1792. */
  1793. Color4.prototype.toArray = function (array, index) {
  1794. if (index === undefined) {
  1795. index = 0;
  1796. }
  1797. array[index] = this.r;
  1798. array[index + 1] = this.g;
  1799. array[index + 2] = this.b;
  1800. array[index + 3] = this.a;
  1801. return this;
  1802. };
  1803. /**
  1804. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1805. * @param right defines the second operand
  1806. * @returns a new Color4 object
  1807. */
  1808. Color4.prototype.add = function (right) {
  1809. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1810. };
  1811. /**
  1812. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1813. * @param right defines the second operand
  1814. * @returns a new Color4 object
  1815. */
  1816. Color4.prototype.subtract = function (right) {
  1817. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1818. };
  1819. /**
  1820. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1821. * @param right defines the second operand
  1822. * @param result defines the Color4 object where to store the result
  1823. * @returns the current Color4 object
  1824. */
  1825. Color4.prototype.subtractToRef = function (right, result) {
  1826. result.r = this.r - right.r;
  1827. result.g = this.g - right.g;
  1828. result.b = this.b - right.b;
  1829. result.a = this.a - right.a;
  1830. return this;
  1831. };
  1832. /**
  1833. * Creates a new Color4 with the current Color4 values multiplied by scale
  1834. * @param scale defines the scaling factor to apply
  1835. * @returns a new Color4 object
  1836. */
  1837. Color4.prototype.scale = function (scale) {
  1838. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1839. };
  1840. /**
  1841. * Multiplies the current Color4 values by scale and stores the result in "result"
  1842. * @param scale defines the scaling factor to apply
  1843. * @param result defines the Color4 object where to store the result
  1844. * @returns the current Color4.
  1845. */
  1846. Color4.prototype.scaleToRef = function (scale, result) {
  1847. result.r = this.r * scale;
  1848. result.g = this.g * scale;
  1849. result.b = this.b * scale;
  1850. result.a = this.a * scale;
  1851. return this;
  1852. };
  1853. /**
  1854. * Clamps the rgb values by the min and max values and stores the result into "result"
  1855. * @param min defines minimum clamping value (default is 0)
  1856. * @param max defines maximum clamping value (default is 1)
  1857. * @param result defines color to store the result into.
  1858. * @returns the cuurent Color4
  1859. */
  1860. Color4.prototype.clampToRef = function (min, max, result) {
  1861. if (min === void 0) { min = 0; }
  1862. if (max === void 0) { max = 1; }
  1863. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1864. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1865. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1866. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1867. return this;
  1868. };
  1869. /**
  1870. * Multipy an Color4 value by another and return a new Color4 object
  1871. * @param color defines the Color4 value to multiply by
  1872. * @returns a new Color4 object
  1873. */
  1874. Color4.prototype.multiply = function (color) {
  1875. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1876. };
  1877. /**
  1878. * Multipy a Color4 value by another and push the result in a reference value
  1879. * @param color defines the Color4 value to multiply by
  1880. * @param result defines the Color4 to fill the result in
  1881. * @returns the result Color4
  1882. */
  1883. Color4.prototype.multiplyToRef = function (color, result) {
  1884. result.r = this.r * color.r;
  1885. result.g = this.g * color.g;
  1886. result.b = this.b * color.b;
  1887. result.a = this.a * color.a;
  1888. return result;
  1889. };
  1890. /**
  1891. * Creates a string with the Color4 current values
  1892. * @returns the string representation of the Color4 object
  1893. */
  1894. Color4.prototype.toString = function () {
  1895. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1896. };
  1897. /**
  1898. * Returns the string "Color4"
  1899. * @returns "Color4"
  1900. */
  1901. Color4.prototype.getClassName = function () {
  1902. return "Color4";
  1903. };
  1904. /**
  1905. * Compute the Color4 hash code
  1906. * @returns an unique number that can be used to hash Color4 objects
  1907. */
  1908. Color4.prototype.getHashCode = function () {
  1909. var hash = this.r || 0;
  1910. hash = (hash * 397) ^ (this.g || 0);
  1911. hash = (hash * 397) ^ (this.b || 0);
  1912. hash = (hash * 397) ^ (this.a || 0);
  1913. return hash;
  1914. };
  1915. /**
  1916. * Creates a new Color4 copied from the current one
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.clone = function () {
  1920. return new Color4(this.r, this.g, this.b, this.a);
  1921. };
  1922. /**
  1923. * Copies the passed Color4 values into the current one
  1924. * @param source defines the source Color4 object
  1925. * @returns the current updated Color4 object
  1926. */
  1927. Color4.prototype.copyFrom = function (source) {
  1928. this.r = source.r;
  1929. this.g = source.g;
  1930. this.b = source.b;
  1931. this.a = source.a;
  1932. return this;
  1933. };
  1934. /**
  1935. * Copies the passed float values into the current one
  1936. * @param r defines the red component to read from
  1937. * @param g defines the green component to read from
  1938. * @param b defines the blue component to read from
  1939. * @param a defines the alpha component to read from
  1940. * @returns the current updated Color4 object
  1941. */
  1942. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1943. this.r = r;
  1944. this.g = g;
  1945. this.b = b;
  1946. this.a = a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Copies the passed float values into the current one
  1951. * @param r defines the red component to read from
  1952. * @param g defines the green component to read from
  1953. * @param b defines the blue component to read from
  1954. * @param a defines the alpha component to read from
  1955. * @returns the current updated Color4 object
  1956. */
  1957. Color4.prototype.set = function (r, g, b, a) {
  1958. return this.copyFromFloats(r, g, b, a);
  1959. };
  1960. /**
  1961. * Compute the Color4 hexadecimal code as a string
  1962. * @returns a string containing the hexadecimal representation of the Color4 object
  1963. */
  1964. Color4.prototype.toHexString = function () {
  1965. var intR = (this.r * 255) | 0;
  1966. var intG = (this.g * 255) | 0;
  1967. var intB = (this.b * 255) | 0;
  1968. var intA = (this.a * 255) | 0;
  1969. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1970. };
  1971. /**
  1972. * Computes a new Color4 converted from the current one to linear space
  1973. * @returns a new Color4 object
  1974. */
  1975. Color4.prototype.toLinearSpace = function () {
  1976. var convertedColor = new Color4();
  1977. this.toLinearSpaceToRef(convertedColor);
  1978. return convertedColor;
  1979. };
  1980. /**
  1981. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1982. * @param convertedColor defines the Color4 object where to store the linear space version
  1983. * @returns the unmodified Color4
  1984. */
  1985. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1986. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1987. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1988. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1989. convertedColor.a = this.a;
  1990. return this;
  1991. };
  1992. /**
  1993. * Computes a new Color4 converted from the current one to gamma space
  1994. * @returns a new Color4 object
  1995. */
  1996. Color4.prototype.toGammaSpace = function () {
  1997. var convertedColor = new Color4();
  1998. this.toGammaSpaceToRef(convertedColor);
  1999. return convertedColor;
  2000. };
  2001. /**
  2002. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2003. * @param convertedColor defines the Color4 object where to store the gamma space version
  2004. * @returns the unmodified Color4
  2005. */
  2006. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2007. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2008. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2009. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2010. convertedColor.a = this.a;
  2011. return this;
  2012. };
  2013. // Statics
  2014. /**
  2015. * Creates a new Color4 from the string containing valid hexadecimal values
  2016. * @param hex defines a string containing valid hexadecimal values
  2017. * @returns a new Color4 object
  2018. */
  2019. Color4.FromHexString = function (hex) {
  2020. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2021. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  2022. return new Color4(0.0, 0.0, 0.0, 0.0);
  2023. }
  2024. var r = parseInt(hex.substring(1, 3), 16);
  2025. var g = parseInt(hex.substring(3, 5), 16);
  2026. var b = parseInt(hex.substring(5, 7), 16);
  2027. var a = parseInt(hex.substring(7, 9), 16);
  2028. return Color4.FromInts(r, g, b, a);
  2029. };
  2030. /**
  2031. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2032. * @param left defines the start value
  2033. * @param right defines the end value
  2034. * @param amount defines the gradient factor
  2035. * @returns a new Color4 object
  2036. */
  2037. Color4.Lerp = function (left, right, amount) {
  2038. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2039. Color4.LerpToRef(left, right, amount, result);
  2040. return result;
  2041. };
  2042. /**
  2043. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2044. * @param left defines the start value
  2045. * @param right defines the end value
  2046. * @param amount defines the gradient factor
  2047. * @param result defines the Color4 object where to store data
  2048. */
  2049. Color4.LerpToRef = function (left, right, amount, result) {
  2050. result.r = left.r + (right.r - left.r) * amount;
  2051. result.g = left.g + (right.g - left.g) * amount;
  2052. result.b = left.b + (right.b - left.b) * amount;
  2053. result.a = left.a + (right.a - left.a) * amount;
  2054. };
  2055. /**
  2056. * Creates a new Color4 from the starting index element of the passed array
  2057. * @param array defines the source array to read from
  2058. * @param offset defines the offset in the source array
  2059. * @returns a new Color4 object
  2060. */
  2061. Color4.FromArray = function (array, offset) {
  2062. if (offset === void 0) { offset = 0; }
  2063. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2064. };
  2065. /**
  2066. * Creates a new Color3 from integer values (< 256)
  2067. * @param r defines the red component to read from (value between 0 and 255)
  2068. * @param g defines the green component to read from (value between 0 and 255)
  2069. * @param b defines the blue component to read from (value between 0 and 255)
  2070. * @param a defines the alpha component to read from (value between 0 and 255)
  2071. * @returns a new Color3 object
  2072. */
  2073. Color4.FromInts = function (r, g, b, a) {
  2074. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2075. };
  2076. /**
  2077. * Check the content of a given array and convert it to an array containing RGBA data
  2078. * If the original array was already containing count * 4 values then it is returned directly
  2079. * @param colors defines the array to check
  2080. * @param count defines the number of RGBA data to expect
  2081. * @returns an array containing count * 4 values (RGBA)
  2082. */
  2083. Color4.CheckColors4 = function (colors, count) {
  2084. // Check if color3 was used
  2085. if (colors.length === count * 3) {
  2086. var colors4 = [];
  2087. for (var index = 0; index < colors.length; index += 3) {
  2088. var newIndex = (index / 3) * 4;
  2089. colors4[newIndex] = colors[index];
  2090. colors4[newIndex + 1] = colors[index + 1];
  2091. colors4[newIndex + 2] = colors[index + 2];
  2092. colors4[newIndex + 3] = 1.0;
  2093. }
  2094. return colors4;
  2095. }
  2096. return colors;
  2097. };
  2098. return Color4;
  2099. }());
  2100. BABYLON.Color4 = Color4;
  2101. var Vector2 = /** @class */ (function () {
  2102. /**
  2103. * Creates a new Vector2 from the passed x and y coordinates.
  2104. */
  2105. function Vector2(x, y) {
  2106. this.x = x;
  2107. this.y = y;
  2108. }
  2109. /**
  2110. * Returns a string with the Vector2 coordinates.
  2111. */
  2112. Vector2.prototype.toString = function () {
  2113. return "{X: " + this.x + " Y:" + this.y + "}";
  2114. };
  2115. /**
  2116. * Returns the string "Vector2"
  2117. */
  2118. Vector2.prototype.getClassName = function () {
  2119. return "Vector2";
  2120. };
  2121. /**
  2122. * Returns the Vector2 hash code as a number.
  2123. */
  2124. Vector2.prototype.getHashCode = function () {
  2125. var hash = this.x || 0;
  2126. hash = (hash * 397) ^ (this.y || 0);
  2127. return hash;
  2128. };
  2129. // Operators
  2130. /**
  2131. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2132. * Returns the Vector2.
  2133. */
  2134. Vector2.prototype.toArray = function (array, index) {
  2135. if (index === void 0) { index = 0; }
  2136. array[index] = this.x;
  2137. array[index + 1] = this.y;
  2138. return this;
  2139. };
  2140. /**
  2141. * Returns a new array with 2 elements : the Vector2 coordinates.
  2142. */
  2143. Vector2.prototype.asArray = function () {
  2144. var result = new Array();
  2145. this.toArray(result, 0);
  2146. return result;
  2147. };
  2148. /**
  2149. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2150. * Returns the updated Vector2.
  2151. */
  2152. Vector2.prototype.copyFrom = function (source) {
  2153. this.x = source.x;
  2154. this.y = source.y;
  2155. return this;
  2156. };
  2157. /**
  2158. * Sets the Vector2 coordinates with the passed floats.
  2159. * Returns the updated Vector2.
  2160. */
  2161. Vector2.prototype.copyFromFloats = function (x, y) {
  2162. this.x = x;
  2163. this.y = y;
  2164. return this;
  2165. };
  2166. /**
  2167. * Sets the Vector2 coordinates with the passed floats.
  2168. * Returns the updated Vector2.
  2169. */
  2170. Vector2.prototype.set = function (x, y) {
  2171. return this.copyFromFloats(x, y);
  2172. };
  2173. /**
  2174. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2175. */
  2176. Vector2.prototype.add = function (otherVector) {
  2177. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2178. };
  2179. /**
  2180. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2181. * Returns the Vector2.
  2182. */
  2183. Vector2.prototype.addToRef = function (otherVector, result) {
  2184. result.x = this.x + otherVector.x;
  2185. result.y = this.y + otherVector.y;
  2186. return this;
  2187. };
  2188. /**
  2189. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2190. * Returns the updated Vector2.
  2191. */
  2192. Vector2.prototype.addInPlace = function (otherVector) {
  2193. this.x += otherVector.x;
  2194. this.y += otherVector.y;
  2195. return this;
  2196. };
  2197. /**
  2198. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2199. */
  2200. Vector2.prototype.addVector3 = function (otherVector) {
  2201. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2202. };
  2203. /**
  2204. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2205. */
  2206. Vector2.prototype.subtract = function (otherVector) {
  2207. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2208. };
  2209. /**
  2210. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2211. * Returns the Vector2.
  2212. */
  2213. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2214. result.x = this.x - otherVector.x;
  2215. result.y = this.y - otherVector.y;
  2216. return this;
  2217. };
  2218. /**
  2219. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2220. * Returns the updated Vector2.
  2221. */
  2222. Vector2.prototype.subtractInPlace = function (otherVector) {
  2223. this.x -= otherVector.x;
  2224. this.y -= otherVector.y;
  2225. return this;
  2226. };
  2227. /**
  2228. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2229. * Returns the updated Vector2.
  2230. */
  2231. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2232. this.x *= otherVector.x;
  2233. this.y *= otherVector.y;
  2234. return this;
  2235. };
  2236. /**
  2237. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2238. */
  2239. Vector2.prototype.multiply = function (otherVector) {
  2240. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2241. };
  2242. /**
  2243. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2244. * Returns the Vector2.
  2245. */
  2246. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2247. result.x = this.x * otherVector.x;
  2248. result.y = this.y * otherVector.y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2253. */
  2254. Vector2.prototype.multiplyByFloats = function (x, y) {
  2255. return new Vector2(this.x * x, this.y * y);
  2256. };
  2257. /**
  2258. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2259. */
  2260. Vector2.prototype.divide = function (otherVector) {
  2261. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2262. };
  2263. /**
  2264. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2265. * Returns the Vector2.
  2266. */
  2267. Vector2.prototype.divideToRef = function (otherVector, result) {
  2268. result.x = this.x / otherVector.x;
  2269. result.y = this.y / otherVector.y;
  2270. return this;
  2271. };
  2272. /**
  2273. * Divides the current Vector3 coordinates by the passed ones.
  2274. * Returns the updated Vector3.
  2275. */
  2276. Vector2.prototype.divideInPlace = function (otherVector) {
  2277. return this.divideToRef(otherVector, this);
  2278. };
  2279. /**
  2280. * Returns a new Vector2 with current Vector2 negated coordinates.
  2281. */
  2282. Vector2.prototype.negate = function () {
  2283. return new Vector2(-this.x, -this.y);
  2284. };
  2285. /**
  2286. * Multiply the Vector2 coordinates by scale.
  2287. * Returns the updated Vector2.
  2288. */
  2289. Vector2.prototype.scaleInPlace = function (scale) {
  2290. this.x *= scale;
  2291. this.y *= scale;
  2292. return this;
  2293. };
  2294. /**
  2295. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2296. */
  2297. Vector2.prototype.scale = function (scale) {
  2298. return new Vector2(this.x * scale, this.y * scale);
  2299. };
  2300. /**
  2301. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2302. */
  2303. Vector2.prototype.equals = function (otherVector) {
  2304. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2305. };
  2306. /**
  2307. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2308. */
  2309. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2310. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2311. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2312. };
  2313. // Properties
  2314. /**
  2315. * Returns the vector length (float).
  2316. */
  2317. Vector2.prototype.length = function () {
  2318. return Math.sqrt(this.x * this.x + this.y * this.y);
  2319. };
  2320. /**
  2321. * Returns the vector squared length (float);
  2322. */
  2323. Vector2.prototype.lengthSquared = function () {
  2324. return (this.x * this.x + this.y * this.y);
  2325. };
  2326. // Methods
  2327. /**
  2328. * Normalize the vector.
  2329. * Returns the updated Vector2.
  2330. */
  2331. Vector2.prototype.normalize = function () {
  2332. var len = this.length();
  2333. if (len === 0)
  2334. return this;
  2335. var num = 1.0 / len;
  2336. this.x *= num;
  2337. this.y *= num;
  2338. return this;
  2339. };
  2340. /**
  2341. * Returns a new Vector2 copied from the Vector2.
  2342. */
  2343. Vector2.prototype.clone = function () {
  2344. return new Vector2(this.x, this.y);
  2345. };
  2346. // Statics
  2347. /**
  2348. * Returns a new Vector2(0, 0)
  2349. */
  2350. Vector2.Zero = function () {
  2351. return new Vector2(0, 0);
  2352. };
  2353. /**
  2354. * Returns a new Vector2(1, 1)
  2355. */
  2356. Vector2.One = function () {
  2357. return new Vector2(1, 1);
  2358. };
  2359. /**
  2360. * Returns a new Vector2 set from the passed index element of the passed array.
  2361. */
  2362. Vector2.FromArray = function (array, offset) {
  2363. if (offset === void 0) { offset = 0; }
  2364. return new Vector2(array[offset], array[offset + 1]);
  2365. };
  2366. /**
  2367. * Sets "result" from the passed index element of the passed array.
  2368. */
  2369. Vector2.FromArrayToRef = function (array, offset, result) {
  2370. result.x = array[offset];
  2371. result.y = array[offset + 1];
  2372. };
  2373. /**
  2374. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2375. */
  2376. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2377. var squared = amount * amount;
  2378. var cubed = amount * squared;
  2379. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2380. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2381. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2382. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2383. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2384. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2385. return new Vector2(x, y);
  2386. };
  2387. /**
  2388. * 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".
  2389. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2390. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2391. */
  2392. Vector2.Clamp = function (value, min, max) {
  2393. var x = value.x;
  2394. x = (x > max.x) ? max.x : x;
  2395. x = (x < min.x) ? min.x : x;
  2396. var y = value.y;
  2397. y = (y > max.y) ? max.y : y;
  2398. y = (y < min.y) ? min.y : y;
  2399. return new Vector2(x, y);
  2400. };
  2401. /**
  2402. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2403. */
  2404. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2405. var squared = amount * amount;
  2406. var cubed = amount * squared;
  2407. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2408. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2409. var part3 = (cubed - (2.0 * squared)) + amount;
  2410. var part4 = cubed - squared;
  2411. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2412. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2413. return new Vector2(x, y);
  2414. };
  2415. /**
  2416. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2417. */
  2418. Vector2.Lerp = function (start, end, amount) {
  2419. var x = start.x + ((end.x - start.x) * amount);
  2420. var y = start.y + ((end.y - start.y) * amount);
  2421. return new Vector2(x, y);
  2422. };
  2423. /**
  2424. * Returns the dot product (float) of the vector "left" and the vector "right".
  2425. */
  2426. Vector2.Dot = function (left, right) {
  2427. return left.x * right.x + left.y * right.y;
  2428. };
  2429. /**
  2430. * Returns a new Vector2 equal to the normalized passed vector.
  2431. */
  2432. Vector2.Normalize = function (vector) {
  2433. var newVector = vector.clone();
  2434. newVector.normalize();
  2435. return newVector;
  2436. };
  2437. /**
  2438. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2439. */
  2440. Vector2.Minimize = function (left, right) {
  2441. var x = (left.x < right.x) ? left.x : right.x;
  2442. var y = (left.y < right.y) ? left.y : right.y;
  2443. return new Vector2(x, y);
  2444. };
  2445. /**
  2446. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2447. */
  2448. Vector2.Maximize = function (left, right) {
  2449. var x = (left.x > right.x) ? left.x : right.x;
  2450. var y = (left.y > right.y) ? left.y : right.y;
  2451. return new Vector2(x, y);
  2452. };
  2453. /**
  2454. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2455. */
  2456. Vector2.Transform = function (vector, transformation) {
  2457. var r = Vector2.Zero();
  2458. Vector2.TransformToRef(vector, transformation, r);
  2459. return r;
  2460. };
  2461. /**
  2462. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2463. */
  2464. Vector2.TransformToRef = function (vector, transformation, result) {
  2465. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2466. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2467. result.x = x;
  2468. result.y = y;
  2469. };
  2470. /**
  2471. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2472. */
  2473. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2474. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2475. var sign = a < 0 ? -1 : 1;
  2476. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2477. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2478. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2479. };
  2480. /**
  2481. * Returns the distance (float) between the vectors "value1" and "value2".
  2482. */
  2483. Vector2.Distance = function (value1, value2) {
  2484. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2485. };
  2486. /**
  2487. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2488. */
  2489. Vector2.DistanceSquared = function (value1, value2) {
  2490. var x = value1.x - value2.x;
  2491. var y = value1.y - value2.y;
  2492. return (x * x) + (y * y);
  2493. };
  2494. /**
  2495. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2496. */
  2497. Vector2.Center = function (value1, value2) {
  2498. var center = value1.add(value2);
  2499. center.scaleInPlace(0.5);
  2500. return center;
  2501. };
  2502. /**
  2503. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2504. */
  2505. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2506. var l2 = Vector2.DistanceSquared(segA, segB);
  2507. if (l2 === 0.0) {
  2508. return Vector2.Distance(p, segA);
  2509. }
  2510. var v = segB.subtract(segA);
  2511. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2512. var proj = segA.add(v.multiplyByFloats(t, t));
  2513. return Vector2.Distance(p, proj);
  2514. };
  2515. return Vector2;
  2516. }());
  2517. BABYLON.Vector2 = Vector2;
  2518. /**
  2519. * Classed used to store (x,y,z) vector representation
  2520. * A Vector3 is the main object used in 3D geometry
  2521. * It can represent etiher the coordinates of a point the space, either a direction
  2522. * Reminder: Babylon.js uses a left handed forward facing system
  2523. */
  2524. var Vector3 = /** @class */ (function () {
  2525. /**
  2526. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2527. * @param x defines the first coordinates (on X axis)
  2528. * @param y defines the second coordinates (on Y axis)
  2529. * @param z defines the third coordinates (on Z axis)
  2530. */
  2531. function Vector3(
  2532. /**
  2533. * Defines the first coordinates (on X axis)
  2534. */
  2535. x,
  2536. /**
  2537. * Defines the second coordinates (on Y axis)
  2538. */
  2539. y,
  2540. /**
  2541. * Defines the third coordinates (on Z axis)
  2542. */
  2543. z) {
  2544. this.x = x;
  2545. this.y = y;
  2546. this.z = z;
  2547. }
  2548. /**
  2549. * Creates a string representation of the Vector3
  2550. * @returns a string with the Vector3 coordinates.
  2551. */
  2552. Vector3.prototype.toString = function () {
  2553. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2554. };
  2555. /**
  2556. * Gets the class name
  2557. * @returns the string "Vector3"
  2558. */
  2559. Vector3.prototype.getClassName = function () {
  2560. return "Vector3";
  2561. };
  2562. /**
  2563. * Creates the Vector3 hash code
  2564. * @returns a number which tends to be unique between Vector3 instances
  2565. */
  2566. Vector3.prototype.getHashCode = function () {
  2567. var hash = this.x || 0;
  2568. hash = (hash * 397) ^ (this.y || 0);
  2569. hash = (hash * 397) ^ (this.z || 0);
  2570. return hash;
  2571. };
  2572. // Operators
  2573. /**
  2574. * Creates an array containing three elements : the coordinates of the Vector3
  2575. * @returns a new array of numbers
  2576. */
  2577. Vector3.prototype.asArray = function () {
  2578. var result = [];
  2579. this.toArray(result, 0);
  2580. return result;
  2581. };
  2582. /**
  2583. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2584. * @param array defines the destination array
  2585. * @param index defines the offset in the destination array
  2586. * @returns the current Vector3
  2587. */
  2588. Vector3.prototype.toArray = function (array, index) {
  2589. if (index === void 0) { index = 0; }
  2590. array[index] = this.x;
  2591. array[index + 1] = this.y;
  2592. array[index + 2] = this.z;
  2593. return this;
  2594. };
  2595. /**
  2596. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2597. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2598. */
  2599. Vector3.prototype.toQuaternion = function () {
  2600. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2601. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2602. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2603. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2604. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2605. var cosy = Math.cos(this.y * 0.5);
  2606. var siny = Math.sin(this.y * 0.5);
  2607. result.x = coszMinusx * siny;
  2608. result.y = -sinzMinusx * siny;
  2609. result.z = sinxPlusz * cosy;
  2610. result.w = cosxPlusz * cosy;
  2611. return result;
  2612. };
  2613. /**
  2614. * Adds the passed vector to the current Vector3
  2615. * @param otherVector defines the second operand
  2616. * @returns the current updated Vector3
  2617. */
  2618. Vector3.prototype.addInPlace = function (otherVector) {
  2619. this.x += otherVector.x;
  2620. this.y += otherVector.y;
  2621. this.z += otherVector.z;
  2622. return this;
  2623. };
  2624. /**
  2625. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2626. * @param otherVector defines the second operand
  2627. * @returns the resulting Vector3
  2628. */
  2629. Vector3.prototype.add = function (otherVector) {
  2630. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2631. };
  2632. /**
  2633. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2634. * @param otherVector defines the second operand
  2635. * @param result defines the Vector3 object where to store the result
  2636. * @returns the current Vector3
  2637. */
  2638. Vector3.prototype.addToRef = function (otherVector, result) {
  2639. result.x = this.x + otherVector.x;
  2640. result.y = this.y + otherVector.y;
  2641. result.z = this.z + otherVector.z;
  2642. return this;
  2643. };
  2644. /**
  2645. * Subtract the passed vector from the current Vector3
  2646. * @param otherVector defines the second operand
  2647. * @returns the current updated Vector3
  2648. */
  2649. Vector3.prototype.subtractInPlace = function (otherVector) {
  2650. this.x -= otherVector.x;
  2651. this.y -= otherVector.y;
  2652. this.z -= otherVector.z;
  2653. return this;
  2654. };
  2655. /**
  2656. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2657. * @param otherVector defines the second operand
  2658. * @returns the resulting Vector3
  2659. */
  2660. Vector3.prototype.subtract = function (otherVector) {
  2661. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2662. };
  2663. /**
  2664. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2665. * @param otherVector defines the second operand
  2666. * @param result defines the Vector3 object where to store the result
  2667. * @returns the current Vector3
  2668. */
  2669. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2670. result.x = this.x - otherVector.x;
  2671. result.y = this.y - otherVector.y;
  2672. result.z = this.z - otherVector.z;
  2673. return this;
  2674. };
  2675. /**
  2676. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2677. * @param x defines the x coordinate of the operand
  2678. * @param y defines the y coordinate of the operand
  2679. * @param z defines the z coordinate of the operand
  2680. * @returns the resulting Vector3
  2681. */
  2682. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2683. return new Vector3(this.x - x, this.y - y, this.z - z);
  2684. };
  2685. /**
  2686. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2687. * @param x defines the x coordinate of the operand
  2688. * @param y defines the y coordinate of the operand
  2689. * @param z defines the z coordinate of the operand
  2690. * @param result defines the Vector3 object where to store the result
  2691. * @returns the current Vector3
  2692. */
  2693. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2694. result.x = this.x - x;
  2695. result.y = this.y - y;
  2696. result.z = this.z - z;
  2697. return this;
  2698. };
  2699. /**
  2700. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2701. * @returns a new Vector3
  2702. */
  2703. Vector3.prototype.negate = function () {
  2704. return new Vector3(-this.x, -this.y, -this.z);
  2705. };
  2706. /**
  2707. * Multiplies the Vector3 coordinates by the float "scale"
  2708. * @param scale defines the multiplier factor
  2709. * @returns the current updated Vector3
  2710. */
  2711. Vector3.prototype.scaleInPlace = function (scale) {
  2712. this.x *= scale;
  2713. this.y *= scale;
  2714. this.z *= scale;
  2715. return this;
  2716. };
  2717. /**
  2718. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2719. * @param scale defines the multiplier factor
  2720. * @returns a new Vector3
  2721. */
  2722. Vector3.prototype.scale = function (scale) {
  2723. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2724. };
  2725. /**
  2726. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2727. * @param scale defines the multiplier factor
  2728. * @param result defines the Vector3 object where to store the result
  2729. * @returns the current Vector3
  2730. */
  2731. Vector3.prototype.scaleToRef = function (scale, result) {
  2732. result.x = this.x * scale;
  2733. result.y = this.y * scale;
  2734. result.z = this.z * scale;
  2735. return this;
  2736. };
  2737. /**
  2738. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2739. * @param otherVector defines the second operand
  2740. * @returns true if both vectors are equals
  2741. */
  2742. Vector3.prototype.equals = function (otherVector) {
  2743. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2744. };
  2745. /**
  2746. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2747. * @param otherVector defines the second operand
  2748. * @param epsilon defines the minimal distance to define values as equals
  2749. * @returns true if both vectors are distant less than epsilon
  2750. */
  2751. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2752. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2753. 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);
  2754. };
  2755. /**
  2756. * Returns true if the current Vector3 coordinates equals the passed floats
  2757. * @param x defines the x coordinate of the operand
  2758. * @param y defines the y coordinate of the operand
  2759. * @param z defines the z coordinate of the operand
  2760. * @returns true if both vectors are equals
  2761. */
  2762. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2763. return this.x === x && this.y === y && this.z === z;
  2764. };
  2765. /**
  2766. * Multiplies the current Vector3 coordinates by the passed ones
  2767. * @param otherVector defines the second operand
  2768. * @returns the current updated Vector3
  2769. */
  2770. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2771. this.x *= otherVector.x;
  2772. this.y *= otherVector.y;
  2773. this.z *= otherVector.z;
  2774. return this;
  2775. };
  2776. /**
  2777. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2778. * @param otherVector defines the second operand
  2779. * @returns the new Vector3
  2780. */
  2781. Vector3.prototype.multiply = function (otherVector) {
  2782. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2783. };
  2784. /**
  2785. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2786. * @param otherVector defines the second operand
  2787. * @param result defines the Vector3 object where to store the result
  2788. * @returns the current Vector3
  2789. */
  2790. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2791. result.x = this.x * otherVector.x;
  2792. result.y = this.y * otherVector.y;
  2793. result.z = this.z * otherVector.z;
  2794. return this;
  2795. };
  2796. /**
  2797. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2798. * @param x defines the x coordinate of the operand
  2799. * @param y defines the y coordinate of the operand
  2800. * @param z defines the z coordinate of the operand
  2801. * @returns the new Vector3
  2802. */
  2803. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2804. return new Vector3(this.x * x, this.y * y, this.z * z);
  2805. };
  2806. /**
  2807. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2808. * @param otherVector defines the second operand
  2809. * @returns the new Vector3
  2810. */
  2811. Vector3.prototype.divide = function (otherVector) {
  2812. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2813. };
  2814. /**
  2815. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2816. * @param otherVector defines the second operand
  2817. * @param result defines the Vector3 object where to store the result
  2818. * @returns the current Vector3
  2819. */
  2820. Vector3.prototype.divideToRef = function (otherVector, result) {
  2821. result.x = this.x / otherVector.x;
  2822. result.y = this.y / otherVector.y;
  2823. result.z = this.z / otherVector.z;
  2824. return this;
  2825. };
  2826. /**
  2827. * Divides the current Vector3 coordinates by the passed ones.
  2828. * @param otherVector defines the second operand
  2829. * @returns the current updated Vector3
  2830. */
  2831. Vector3.prototype.divideInPlace = function (otherVector) {
  2832. return this.divideToRef(otherVector, this);
  2833. };
  2834. /**
  2835. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2836. * @param other defines the second operand
  2837. * @returns the current updated Vector3
  2838. */
  2839. Vector3.prototype.minimizeInPlace = function (other) {
  2840. if (other.x < this.x)
  2841. this.x = other.x;
  2842. if (other.y < this.y)
  2843. this.y = other.y;
  2844. if (other.z < this.z)
  2845. this.z = other.z;
  2846. return this;
  2847. };
  2848. /**
  2849. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2850. * @param other defines the second operand
  2851. * @returns the current updated Vector3
  2852. */
  2853. Vector3.prototype.maximizeInPlace = function (other) {
  2854. if (other.x > this.x)
  2855. this.x = other.x;
  2856. if (other.y > this.y)
  2857. this.y = other.y;
  2858. if (other.z > this.z)
  2859. this.z = other.z;
  2860. return this;
  2861. };
  2862. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2863. /**
  2864. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2865. */
  2866. get: function () {
  2867. var absX = Math.abs(this.x);
  2868. var absY = Math.abs(this.y);
  2869. if (absX !== absY) {
  2870. return true;
  2871. }
  2872. var absZ = Math.abs(this.z);
  2873. if (absX !== absZ) {
  2874. return true;
  2875. }
  2876. if (absY !== absZ) {
  2877. return true;
  2878. }
  2879. return false;
  2880. },
  2881. enumerable: true,
  2882. configurable: true
  2883. });
  2884. // Properties
  2885. /**
  2886. * Gets the length of the Vector3
  2887. * @returns the length of the Vecto3
  2888. */
  2889. Vector3.prototype.length = function () {
  2890. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2891. };
  2892. /**
  2893. * Gets the squared length of the Vector3
  2894. * @returns squared length of the Vector3
  2895. */
  2896. Vector3.prototype.lengthSquared = function () {
  2897. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2898. };
  2899. /**
  2900. * Normalize the current Vector3.
  2901. * Please note that this is an in place operation.
  2902. * @returns the current updated Vector3
  2903. */
  2904. Vector3.prototype.normalize = function () {
  2905. var len = this.length();
  2906. if (len === 0 || len === 1.0)
  2907. return this;
  2908. var num = 1.0 / len;
  2909. this.x *= num;
  2910. this.y *= num;
  2911. this.z *= num;
  2912. return this;
  2913. };
  2914. /**
  2915. * Normalize the current Vector3 to a new vector
  2916. * @returns the new Vector3
  2917. */
  2918. Vector3.prototype.normalizeToNew = function () {
  2919. var normalized = new Vector3(0, 0, 0);
  2920. this.normalizeToRef(normalized);
  2921. return normalized;
  2922. };
  2923. /**
  2924. * Normalize the current Vector3 to the reference
  2925. * @param reference define the Vector3 to update
  2926. * @returns the updated Vector3
  2927. */
  2928. Vector3.prototype.normalizeToRef = function (reference) {
  2929. var len = this.length();
  2930. if (len === 0 || len === 1.0) {
  2931. reference.set(this.x, this.y, this.z);
  2932. return reference;
  2933. }
  2934. var scale = 1.0 / len;
  2935. this.scaleToRef(scale, reference);
  2936. return reference;
  2937. };
  2938. /**
  2939. * Creates a new Vector3 copied from the current Vector3
  2940. * @returns the new Vector3
  2941. */
  2942. Vector3.prototype.clone = function () {
  2943. return new Vector3(this.x, this.y, this.z);
  2944. };
  2945. /**
  2946. * Copies the passed vector coordinates to the current Vector3 ones
  2947. * @param source defines the source Vector3
  2948. * @returns the current updated Vector3
  2949. */
  2950. Vector3.prototype.copyFrom = function (source) {
  2951. this.x = source.x;
  2952. this.y = source.y;
  2953. this.z = source.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Copies the passed floats to the current Vector3 coordinates
  2958. * @param x defines the x coordinate of the operand
  2959. * @param y defines the y coordinate of the operand
  2960. * @param z defines the z coordinate of the operand
  2961. * @returns the current updated Vector3
  2962. */
  2963. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2964. this.x = x;
  2965. this.y = y;
  2966. this.z = z;
  2967. return this;
  2968. };
  2969. /**
  2970. * Copies the passed floats to the current Vector3 coordinates
  2971. * @param x defines the x coordinate of the operand
  2972. * @param y defines the y coordinate of the operand
  2973. * @param z defines the z coordinate of the operand
  2974. * @returns the current updated Vector3
  2975. */
  2976. Vector3.prototype.set = function (x, y, z) {
  2977. return this.copyFromFloats(x, y, z);
  2978. };
  2979. // Statics
  2980. /**
  2981. * Get the clip factor between two vectors
  2982. * @param vector0 defines the first operand
  2983. * @param vector1 defines the second operand
  2984. * @param axis defines the axis to use
  2985. * @param size defines the size along the axis
  2986. * @returns the clip factor
  2987. */
  2988. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2989. var d0 = Vector3.Dot(vector0, axis) - size;
  2990. var d1 = Vector3.Dot(vector1, axis) - size;
  2991. var s = d0 / (d0 - d1);
  2992. return s;
  2993. };
  2994. /**
  2995. * Get angle between two vectors
  2996. * @param vector0 angle between vector0 and vector1
  2997. * @param vector1 angle between vector0 and vector1
  2998. * @param normal direction of the normal
  2999. * @return the angle between vector0 and vector1
  3000. */
  3001. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3002. var v0 = vector0.clone().normalize();
  3003. var v1 = vector1.clone().normalize();
  3004. var dot = Vector3.Dot(v0, v1);
  3005. var n = Vector3.Cross(v0, v1);
  3006. if (Vector3.Dot(n, normal) > 0) {
  3007. return Math.acos(dot);
  3008. }
  3009. return -Math.acos(dot);
  3010. };
  3011. /**
  3012. * Returns a new Vector3 set from the index "offset" of the passed array
  3013. * @param array defines the source array
  3014. * @param offset defines the offset in the source array
  3015. * @returns the new Vector3
  3016. */
  3017. Vector3.FromArray = function (array, offset) {
  3018. if (!offset) {
  3019. offset = 0;
  3020. }
  3021. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3022. };
  3023. /**
  3024. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3025. * This function is deprecated. Use FromArray instead
  3026. * @param array defines the source array
  3027. * @param offset defines the offset in the source array
  3028. * @returns the new Vector3
  3029. */
  3030. Vector3.FromFloatArray = function (array, offset) {
  3031. return Vector3.FromArray(array, offset);
  3032. };
  3033. /**
  3034. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3035. * @param array defines the source array
  3036. * @param offset defines the offset in the source array
  3037. * @param result defines the Vector3 where to store the result
  3038. */
  3039. Vector3.FromArrayToRef = function (array, offset, result) {
  3040. result.x = array[offset];
  3041. result.y = array[offset + 1];
  3042. result.z = array[offset + 2];
  3043. };
  3044. /**
  3045. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3046. * This function is deprecated. Use FromArrayToRef instead.
  3047. * @param array defines the source array
  3048. * @param offset defines the offset in the source array
  3049. * @param result defines the Vector3 where to store the result
  3050. */
  3051. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3052. return Vector3.FromArrayToRef(array, offset, result);
  3053. };
  3054. /**
  3055. * Sets the passed vector "result" with the passed floats.
  3056. * @param x defines the x coordinate of the source
  3057. * @param y defines the y coordinate of the source
  3058. * @param z defines the z coordinate of the source
  3059. * @param result defines the Vector3 where to store the result
  3060. */
  3061. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3062. result.x = x;
  3063. result.y = y;
  3064. result.z = z;
  3065. };
  3066. /**
  3067. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3068. * @returns a new empty Vector3
  3069. */
  3070. Vector3.Zero = function () {
  3071. return new Vector3(0.0, 0.0, 0.0);
  3072. };
  3073. /**
  3074. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3075. * @returns a new unit Vector3
  3076. */
  3077. Vector3.One = function () {
  3078. return new Vector3(1.0, 1.0, 1.0);
  3079. };
  3080. /**
  3081. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3082. * @returns a new up Vector3
  3083. */
  3084. Vector3.Up = function () {
  3085. return new Vector3(0.0, 1.0, 0.0);
  3086. };
  3087. /**
  3088. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3089. * @returns a new forward Vector3
  3090. */
  3091. Vector3.Forward = function () {
  3092. return new Vector3(0.0, 0.0, 1.0);
  3093. };
  3094. /**
  3095. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3096. * @returns a new right Vector3
  3097. */
  3098. Vector3.Right = function () {
  3099. return new Vector3(1.0, 0.0, 0.0);
  3100. };
  3101. /**
  3102. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3103. * @returns a new left Vector3
  3104. */
  3105. Vector3.Left = function () {
  3106. return new Vector3(-1.0, 0.0, 0.0);
  3107. };
  3108. /**
  3109. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3110. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3111. * @param vector defines the Vector3 to transform
  3112. * @param transformation defines the transformation matrix
  3113. * @returns the transformed Vector3
  3114. */
  3115. Vector3.TransformCoordinates = function (vector, transformation) {
  3116. var result = Vector3.Zero();
  3117. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3118. return result;
  3119. };
  3120. /**
  3121. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3122. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3123. * @param vector defines the Vector3 to transform
  3124. * @param transformation defines the transformation matrix
  3125. * @param result defines the Vector3 where to store the result
  3126. */
  3127. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3128. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3129. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3130. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3131. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3132. result.x = x / w;
  3133. result.y = y / w;
  3134. result.z = z / w;
  3135. };
  3136. /**
  3137. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3138. * This method computes tranformed coordinates only, not transformed direction vectors
  3139. * @param x define the x coordinate of the source vector
  3140. * @param y define the y coordinate of the source vector
  3141. * @param z define the z coordinate of the source vector
  3142. * @param transformation defines the transformation matrix
  3143. * @param result defines the Vector3 where to store the result
  3144. */
  3145. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3146. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3147. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3148. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3149. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3150. result.x = rx / rw;
  3151. result.y = ry / rw;
  3152. result.z = rz / rw;
  3153. };
  3154. /**
  3155. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3156. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3157. * @param vector defines the Vector3 to transform
  3158. * @param transformation defines the transformation matrix
  3159. * @returns the new Vector3
  3160. */
  3161. Vector3.TransformNormal = function (vector, transformation) {
  3162. var result = Vector3.Zero();
  3163. Vector3.TransformNormalToRef(vector, transformation, result);
  3164. return result;
  3165. };
  3166. /**
  3167. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3168. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3169. * @param vector defines the Vector3 to transform
  3170. * @param transformation defines the transformation matrix
  3171. * @param result defines the Vector3 where to store the result
  3172. */
  3173. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3174. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3175. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3176. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3177. result.x = x;
  3178. result.y = y;
  3179. result.z = z;
  3180. };
  3181. /**
  3182. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3183. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3184. * @param x define the x coordinate of the source vector
  3185. * @param y define the y coordinate of the source vector
  3186. * @param z define the z coordinate of the source vector
  3187. * @param transformation defines the transformation matrix
  3188. * @param result defines the Vector3 where to store the result
  3189. */
  3190. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3191. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3192. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3193. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3197. * @param value1 defines the first control point
  3198. * @param value2 defines the second control point
  3199. * @param value3 defines the third control point
  3200. * @param value4 defines the fourth control point
  3201. * @param amount defines the amount on the spline to use
  3202. * @returns the new Vector3
  3203. */
  3204. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3205. var squared = amount * amount;
  3206. var cubed = amount * squared;
  3207. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3208. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3209. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3210. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3211. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3212. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3213. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3214. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3215. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3216. return new Vector3(x, y, z);
  3217. };
  3218. /**
  3219. * 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"
  3220. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3221. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3222. * @param value defines the current value
  3223. * @param min defines the lower range value
  3224. * @param max defines the upper range value
  3225. * @returns the new Vector3
  3226. */
  3227. Vector3.Clamp = function (value, min, max) {
  3228. var x = value.x;
  3229. x = (x > max.x) ? max.x : x;
  3230. x = (x < min.x) ? min.x : x;
  3231. var y = value.y;
  3232. y = (y > max.y) ? max.y : y;
  3233. y = (y < min.y) ? min.y : y;
  3234. var z = value.z;
  3235. z = (z > max.z) ? max.z : z;
  3236. z = (z < min.z) ? min.z : z;
  3237. return new Vector3(x, y, z);
  3238. };
  3239. /**
  3240. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3241. * @param value1 defines the first control point
  3242. * @param tangent1 defines the first tangent vector
  3243. * @param value2 defines the second control point
  3244. * @param tangent2 defines the second tangent vector
  3245. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3246. * @returns the new Vector3
  3247. */
  3248. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3249. var squared = amount * amount;
  3250. var cubed = amount * squared;
  3251. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3252. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3253. var part3 = (cubed - (2.0 * squared)) + amount;
  3254. var part4 = cubed - squared;
  3255. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3256. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3257. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3258. return new Vector3(x, y, z);
  3259. };
  3260. /**
  3261. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3262. * @param start defines the start value
  3263. * @param end defines the end value
  3264. * @param amount max defines amount between both (between 0 and 1)
  3265. * @returns the new Vector3
  3266. */
  3267. Vector3.Lerp = function (start, end, amount) {
  3268. var result = new Vector3(0, 0, 0);
  3269. Vector3.LerpToRef(start, end, amount, result);
  3270. return result;
  3271. };
  3272. /**
  3273. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3274. * @param start defines the start value
  3275. * @param end defines the end value
  3276. * @param amount max defines amount between both (between 0 and 1)
  3277. * @param result defines the Vector3 where to store the result
  3278. */
  3279. Vector3.LerpToRef = function (start, end, amount, result) {
  3280. result.x = start.x + ((end.x - start.x) * amount);
  3281. result.y = start.y + ((end.y - start.y) * amount);
  3282. result.z = start.z + ((end.z - start.z) * amount);
  3283. };
  3284. /**
  3285. * Returns the dot product (float) between the vectors "left" and "right"
  3286. * @param left defines the left operand
  3287. * @param right defines the right operand
  3288. * @returns the dot product
  3289. */
  3290. Vector3.Dot = function (left, right) {
  3291. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3292. };
  3293. /**
  3294. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3295. * The cross product is then orthogonal to both "left" and "right"
  3296. * @param left defines the left operand
  3297. * @param right defines the right operand
  3298. * @returns the cross product
  3299. */
  3300. Vector3.Cross = function (left, right) {
  3301. var result = Vector3.Zero();
  3302. Vector3.CrossToRef(left, right, result);
  3303. return result;
  3304. };
  3305. /**
  3306. * Sets the passed vector "result" with the cross product of "left" and "right"
  3307. * The cross product is then orthogonal to both "left" and "right"
  3308. * @param left defines the left operand
  3309. * @param right defines the right operand
  3310. * @param result defines the Vector3 where to store the result
  3311. */
  3312. Vector3.CrossToRef = function (left, right, result) {
  3313. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3314. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3315. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3316. result.copyFrom(MathTmp.Vector3[0]);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 as the normalization of the passed vector
  3320. * @param vector defines the Vector3 to normalize
  3321. * @returns the new Vector3
  3322. */
  3323. Vector3.Normalize = function (vector) {
  3324. var result = Vector3.Zero();
  3325. Vector3.NormalizeToRef(vector, result);
  3326. return result;
  3327. };
  3328. /**
  3329. * Sets the passed vector "result" with the normalization of the passed first vector
  3330. * @param vector defines the Vector3 to normalize
  3331. * @param result defines the Vector3 where to store the result
  3332. */
  3333. Vector3.NormalizeToRef = function (vector, result) {
  3334. result.copyFrom(vector);
  3335. result.normalize();
  3336. };
  3337. /**
  3338. * Project a Vector3 onto screen space
  3339. * @param vector defines the Vector3 to project
  3340. * @param world defines the world matrix to use
  3341. * @param transform defines the transform (view x projection) matrix to use
  3342. * @param viewport defines the screen viewport to use
  3343. * @returns the new Vector3
  3344. */
  3345. Vector3.Project = function (vector, world, transform, viewport) {
  3346. var cw = viewport.width;
  3347. var ch = viewport.height;
  3348. var cx = viewport.x;
  3349. var cy = viewport.y;
  3350. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3351. 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);
  3352. var matrix = MathTmp.Matrix[0];
  3353. world.multiplyToRef(transform, matrix);
  3354. matrix.multiplyToRef(viewportMatrix, matrix);
  3355. return Vector3.TransformCoordinates(vector, matrix);
  3356. };
  3357. /**
  3358. * Unproject from screen space to object space
  3359. * @param source defines the screen space Vector3 to use
  3360. * @param viewportWidth defines the current width of the viewport
  3361. * @param viewportHeight defines the current height of the viewport
  3362. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3363. * @param transform defines the transform (view x projection) matrix to use
  3364. * @returns the new Vector3
  3365. */
  3366. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3367. var matrix = MathTmp.Matrix[0];
  3368. world.multiplyToRef(transform, matrix);
  3369. matrix.invert();
  3370. source.x = source.x / viewportWidth * 2 - 1;
  3371. source.y = -(source.y / viewportHeight * 2 - 1);
  3372. var vector = Vector3.TransformCoordinates(source, matrix);
  3373. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3374. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3375. vector = vector.scale(1.0 / num);
  3376. }
  3377. return vector;
  3378. };
  3379. /**
  3380. * Unproject from screen space to object space
  3381. * @param source defines the screen space Vector3 to use
  3382. * @param viewportWidth defines the current width of the viewport
  3383. * @param viewportHeight defines the current height of the viewport
  3384. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3385. * @param view defines the view matrix to use
  3386. * @param projection defines the projection matrix to use
  3387. * @returns the new Vector3
  3388. */
  3389. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3390. var result = Vector3.Zero();
  3391. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3392. return result;
  3393. };
  3394. /**
  3395. * Unproject from screen space to object space
  3396. * @param source defines the screen space Vector3 to use
  3397. * @param viewportWidth defines the current width of the viewport
  3398. * @param viewportHeight defines the current height of the viewport
  3399. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3400. * @param view defines the view matrix to use
  3401. * @param projection defines the projection matrix to use
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3405. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3406. };
  3407. /**
  3408. * Unproject from screen space to object space
  3409. * @param sourceX defines the screen space x coordinate to use
  3410. * @param sourceY defines the screen space y coordinate to use
  3411. * @param sourceZ defines the screen space z coordinate to use
  3412. * @param viewportWidth defines the current width of the viewport
  3413. * @param viewportHeight defines the current height of the viewport
  3414. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3415. * @param view defines the view matrix to use
  3416. * @param projection defines the projection matrix to use
  3417. * @param result defines the Vector3 where to store the result
  3418. */
  3419. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3420. var matrix = MathTmp.Matrix[0];
  3421. world.multiplyToRef(view, matrix);
  3422. matrix.multiplyToRef(projection, matrix);
  3423. matrix.invert();
  3424. var screenSource = MathTmp.Vector3[0];
  3425. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3426. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3427. screenSource.z = 2 * sourceZ - 1.0;
  3428. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3429. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3430. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3431. result.scaleInPlace(1.0 / num);
  3432. }
  3433. };
  3434. /**
  3435. * Gets the minimal coordinate values between two Vector3
  3436. * @param left defines the first operand
  3437. * @param right defines the second operand
  3438. * @returns the new Vector3
  3439. */
  3440. Vector3.Minimize = function (left, right) {
  3441. var min = left.clone();
  3442. min.minimizeInPlace(right);
  3443. return min;
  3444. };
  3445. /**
  3446. * Gets the maximal coordinate values between two Vector3
  3447. * @param left defines the first operand
  3448. * @param right defines the second operand
  3449. * @returns the new Vector3
  3450. */
  3451. Vector3.Maximize = function (left, right) {
  3452. var max = left.clone();
  3453. max.maximizeInPlace(right);
  3454. return max;
  3455. };
  3456. /**
  3457. * Returns the distance between the vectors "value1" and "value2"
  3458. * @param value1 defines the first operand
  3459. * @param value2 defines the second operand
  3460. * @returns the distance
  3461. */
  3462. Vector3.Distance = function (value1, value2) {
  3463. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3464. };
  3465. /**
  3466. * Returns the squared distance between the vectors "value1" and "value2"
  3467. * @param value1 defines the first operand
  3468. * @param value2 defines the second operand
  3469. * @returns the squared distance
  3470. */
  3471. Vector3.DistanceSquared = function (value1, value2) {
  3472. var x = value1.x - value2.x;
  3473. var y = value1.y - value2.y;
  3474. var z = value1.z - value2.z;
  3475. return (x * x) + (y * y) + (z * z);
  3476. };
  3477. /**
  3478. * Returns a new Vector3 located at the center between "value1" and "value2"
  3479. * @param value1 defines the first operand
  3480. * @param value2 defines the second operand
  3481. * @returns the new Vector3
  3482. */
  3483. Vector3.Center = function (value1, value2) {
  3484. var center = value1.add(value2);
  3485. center.scaleInPlace(0.5);
  3486. return center;
  3487. };
  3488. /**
  3489. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3490. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3491. * to something in order to rotate it from its local system to the given target system
  3492. * Note: axis1, axis2 and axis3 are normalized during this operation
  3493. * @param axis1 defines the first axis
  3494. * @param axis2 defines the second axis
  3495. * @param axis3 defines the third axis
  3496. * @returns a new Vector3
  3497. */
  3498. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3499. var rotation = Vector3.Zero();
  3500. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3501. return rotation;
  3502. };
  3503. /**
  3504. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3505. * @param axis1 defines the first axis
  3506. * @param axis2 defines the second axis
  3507. * @param axis3 defines the third axis
  3508. * @param ref defines the Vector3 where to store the result
  3509. */
  3510. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3511. var quat = MathTmp.Quaternion[0];
  3512. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3513. quat.toEulerAnglesToRef(ref);
  3514. };
  3515. return Vector3;
  3516. }());
  3517. BABYLON.Vector3 = Vector3;
  3518. //Vector4 class created for EulerAngle class conversion to Quaternion
  3519. var Vector4 = /** @class */ (function () {
  3520. /**
  3521. * Creates a Vector4 object from the passed floats.
  3522. */
  3523. function Vector4(x, y, z, w) {
  3524. this.x = x;
  3525. this.y = y;
  3526. this.z = z;
  3527. this.w = w;
  3528. }
  3529. /**
  3530. * Returns the string with the Vector4 coordinates.
  3531. */
  3532. Vector4.prototype.toString = function () {
  3533. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3534. };
  3535. /**
  3536. * Returns the string "Vector4".
  3537. */
  3538. Vector4.prototype.getClassName = function () {
  3539. return "Vector4";
  3540. };
  3541. /**
  3542. * Returns the Vector4 hash code.
  3543. */
  3544. Vector4.prototype.getHashCode = function () {
  3545. var hash = this.x || 0;
  3546. hash = (hash * 397) ^ (this.y || 0);
  3547. hash = (hash * 397) ^ (this.z || 0);
  3548. hash = (hash * 397) ^ (this.w || 0);
  3549. return hash;
  3550. };
  3551. // Operators
  3552. /**
  3553. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3554. */
  3555. Vector4.prototype.asArray = function () {
  3556. var result = new Array();
  3557. this.toArray(result, 0);
  3558. return result;
  3559. };
  3560. /**
  3561. * Populates the passed array from the passed index with the Vector4 coordinates.
  3562. * Returns the Vector4.
  3563. */
  3564. Vector4.prototype.toArray = function (array, index) {
  3565. if (index === undefined) {
  3566. index = 0;
  3567. }
  3568. array[index] = this.x;
  3569. array[index + 1] = this.y;
  3570. array[index + 2] = this.z;
  3571. array[index + 3] = this.w;
  3572. return this;
  3573. };
  3574. /**
  3575. * Adds the passed vector to the current Vector4.
  3576. * Returns the updated Vector4.
  3577. */
  3578. Vector4.prototype.addInPlace = function (otherVector) {
  3579. this.x += otherVector.x;
  3580. this.y += otherVector.y;
  3581. this.z += otherVector.z;
  3582. this.w += otherVector.w;
  3583. return this;
  3584. };
  3585. /**
  3586. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3587. */
  3588. Vector4.prototype.add = function (otherVector) {
  3589. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3590. };
  3591. /**
  3592. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3593. * Returns the current Vector4.
  3594. */
  3595. Vector4.prototype.addToRef = function (otherVector, result) {
  3596. result.x = this.x + otherVector.x;
  3597. result.y = this.y + otherVector.y;
  3598. result.z = this.z + otherVector.z;
  3599. result.w = this.w + otherVector.w;
  3600. return this;
  3601. };
  3602. /**
  3603. * Subtract in place the passed vector from the current Vector4.
  3604. * Returns the updated Vector4.
  3605. */
  3606. Vector4.prototype.subtractInPlace = function (otherVector) {
  3607. this.x -= otherVector.x;
  3608. this.y -= otherVector.y;
  3609. this.z -= otherVector.z;
  3610. this.w -= otherVector.w;
  3611. return this;
  3612. };
  3613. /**
  3614. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3615. */
  3616. Vector4.prototype.subtract = function (otherVector) {
  3617. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3618. };
  3619. /**
  3620. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3621. * Returns the current Vector4.
  3622. */
  3623. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3624. result.x = this.x - otherVector.x;
  3625. result.y = this.y - otherVector.y;
  3626. result.z = this.z - otherVector.z;
  3627. result.w = this.w - otherVector.w;
  3628. return this;
  3629. };
  3630. /**
  3631. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3632. */
  3633. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3634. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3635. };
  3636. /**
  3637. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3638. * Returns the current Vector4.
  3639. */
  3640. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3641. result.x = this.x - x;
  3642. result.y = this.y - y;
  3643. result.z = this.z - z;
  3644. result.w = this.w - w;
  3645. return this;
  3646. };
  3647. /**
  3648. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3649. */
  3650. Vector4.prototype.negate = function () {
  3651. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3652. };
  3653. /**
  3654. * Multiplies the current Vector4 coordinates by scale (float).
  3655. * Returns the updated Vector4.
  3656. */
  3657. Vector4.prototype.scaleInPlace = function (scale) {
  3658. this.x *= scale;
  3659. this.y *= scale;
  3660. this.z *= scale;
  3661. this.w *= scale;
  3662. return this;
  3663. };
  3664. /**
  3665. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3666. */
  3667. Vector4.prototype.scale = function (scale) {
  3668. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3669. };
  3670. /**
  3671. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3672. * Returns the current Vector4.
  3673. */
  3674. Vector4.prototype.scaleToRef = function (scale, result) {
  3675. result.x = this.x * scale;
  3676. result.y = this.y * scale;
  3677. result.z = this.z * scale;
  3678. result.w = this.w * scale;
  3679. return this;
  3680. };
  3681. /**
  3682. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3683. */
  3684. Vector4.prototype.equals = function (otherVector) {
  3685. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3686. };
  3687. /**
  3688. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3689. */
  3690. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3691. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3692. return otherVector
  3693. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3694. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3695. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3696. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3697. };
  3698. /**
  3699. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3700. */
  3701. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3702. return this.x === x && this.y === y && this.z === z && this.w === w;
  3703. };
  3704. /**
  3705. * Multiplies in place the current Vector4 by the passed one.
  3706. * Returns the updated Vector4.
  3707. */
  3708. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3709. this.x *= otherVector.x;
  3710. this.y *= otherVector.y;
  3711. this.z *= otherVector.z;
  3712. this.w *= otherVector.w;
  3713. return this;
  3714. };
  3715. /**
  3716. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3717. */
  3718. Vector4.prototype.multiply = function (otherVector) {
  3719. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3720. };
  3721. /**
  3722. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3723. * Returns the current Vector4.
  3724. */
  3725. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3726. result.x = this.x * otherVector.x;
  3727. result.y = this.y * otherVector.y;
  3728. result.z = this.z * otherVector.z;
  3729. result.w = this.w * otherVector.w;
  3730. return this;
  3731. };
  3732. /**
  3733. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3734. */
  3735. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3736. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3737. };
  3738. /**
  3739. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3740. */
  3741. Vector4.prototype.divide = function (otherVector) {
  3742. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3743. };
  3744. /**
  3745. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3746. * Returns the current Vector4.
  3747. */
  3748. Vector4.prototype.divideToRef = function (otherVector, result) {
  3749. result.x = this.x / otherVector.x;
  3750. result.y = this.y / otherVector.y;
  3751. result.z = this.z / otherVector.z;
  3752. result.w = this.w / otherVector.w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Divides the current Vector3 coordinates by the passed ones.
  3757. * @returns the updated Vector3.
  3758. */
  3759. Vector4.prototype.divideInPlace = function (otherVector) {
  3760. return this.divideToRef(otherVector, this);
  3761. };
  3762. /**
  3763. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3764. * @param other defines the second operand
  3765. * @returns the current updated Vector4
  3766. */
  3767. Vector4.prototype.minimizeInPlace = function (other) {
  3768. if (other.x < this.x)
  3769. this.x = other.x;
  3770. if (other.y < this.y)
  3771. this.y = other.y;
  3772. if (other.z < this.z)
  3773. this.z = other.z;
  3774. if (other.w < this.w)
  3775. this.w = other.w;
  3776. return this;
  3777. };
  3778. /**
  3779. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3780. * @param other defines the second operand
  3781. * @returns the current updated Vector4
  3782. */
  3783. Vector4.prototype.maximizeInPlace = function (other) {
  3784. if (other.x > this.x)
  3785. this.x = other.x;
  3786. if (other.y > this.y)
  3787. this.y = other.y;
  3788. if (other.z > this.z)
  3789. this.z = other.z;
  3790. if (other.w > this.w)
  3791. this.w = other.w;
  3792. return this;
  3793. };
  3794. // Properties
  3795. /**
  3796. * Returns the Vector4 length (float).
  3797. */
  3798. Vector4.prototype.length = function () {
  3799. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3800. };
  3801. /**
  3802. * Returns the Vector4 squared length (float).
  3803. */
  3804. Vector4.prototype.lengthSquared = function () {
  3805. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3806. };
  3807. // Methods
  3808. /**
  3809. * Normalizes in place the Vector4.
  3810. * Returns the updated Vector4.
  3811. */
  3812. Vector4.prototype.normalize = function () {
  3813. var len = this.length();
  3814. if (len === 0)
  3815. return this;
  3816. var num = 1.0 / len;
  3817. this.x *= num;
  3818. this.y *= num;
  3819. this.z *= num;
  3820. this.w *= num;
  3821. return this;
  3822. };
  3823. /**
  3824. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3825. */
  3826. Vector4.prototype.toVector3 = function () {
  3827. return new Vector3(this.x, this.y, this.z);
  3828. };
  3829. /**
  3830. * Returns a new Vector4 copied from the current one.
  3831. */
  3832. Vector4.prototype.clone = function () {
  3833. return new Vector4(this.x, this.y, this.z, this.w);
  3834. };
  3835. /**
  3836. * Updates the current Vector4 with the passed one coordinates.
  3837. * Returns the updated Vector4.
  3838. */
  3839. Vector4.prototype.copyFrom = function (source) {
  3840. this.x = source.x;
  3841. this.y = source.y;
  3842. this.z = source.z;
  3843. this.w = source.w;
  3844. return this;
  3845. };
  3846. /**
  3847. * Updates the current Vector4 coordinates with the passed floats.
  3848. * Returns the updated Vector4.
  3849. */
  3850. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3851. this.x = x;
  3852. this.y = y;
  3853. this.z = z;
  3854. this.w = w;
  3855. return this;
  3856. };
  3857. /**
  3858. * Updates the current Vector4 coordinates with the passed floats.
  3859. * Returns the updated Vector4.
  3860. */
  3861. Vector4.prototype.set = function (x, y, z, w) {
  3862. return this.copyFromFloats(x, y, z, w);
  3863. };
  3864. // Statics
  3865. /**
  3866. * Returns a new Vector4 set from the starting index of the passed array.
  3867. */
  3868. Vector4.FromArray = function (array, offset) {
  3869. if (!offset) {
  3870. offset = 0;
  3871. }
  3872. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3873. };
  3874. /**
  3875. * Updates the passed vector "result" from the starting index of the passed array.
  3876. */
  3877. Vector4.FromArrayToRef = function (array, offset, result) {
  3878. result.x = array[offset];
  3879. result.y = array[offset + 1];
  3880. result.z = array[offset + 2];
  3881. result.w = array[offset + 3];
  3882. };
  3883. /**
  3884. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3885. */
  3886. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3887. Vector4.FromArrayToRef(array, offset, result);
  3888. };
  3889. /**
  3890. * Updates the passed vector "result" coordinates from the passed floats.
  3891. */
  3892. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3893. result.x = x;
  3894. result.y = y;
  3895. result.z = z;
  3896. result.w = w;
  3897. };
  3898. /**
  3899. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3900. */
  3901. Vector4.Zero = function () {
  3902. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3903. };
  3904. /**
  3905. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3906. */
  3907. Vector4.One = function () {
  3908. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3909. };
  3910. /**
  3911. * Returns a new normalized Vector4 from the passed one.
  3912. */
  3913. Vector4.Normalize = function (vector) {
  3914. var result = Vector4.Zero();
  3915. Vector4.NormalizeToRef(vector, result);
  3916. return result;
  3917. };
  3918. /**
  3919. * Updates the passed vector "result" from the normalization of the passed one.
  3920. */
  3921. Vector4.NormalizeToRef = function (vector, result) {
  3922. result.copyFrom(vector);
  3923. result.normalize();
  3924. };
  3925. Vector4.Minimize = function (left, right) {
  3926. var min = left.clone();
  3927. min.minimizeInPlace(right);
  3928. return min;
  3929. };
  3930. Vector4.Maximize = function (left, right) {
  3931. var max = left.clone();
  3932. max.maximizeInPlace(right);
  3933. return max;
  3934. };
  3935. /**
  3936. * Returns the distance (float) between the vectors "value1" and "value2".
  3937. */
  3938. Vector4.Distance = function (value1, value2) {
  3939. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3940. };
  3941. /**
  3942. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3943. */
  3944. Vector4.DistanceSquared = function (value1, value2) {
  3945. var x = value1.x - value2.x;
  3946. var y = value1.y - value2.y;
  3947. var z = value1.z - value2.z;
  3948. var w = value1.w - value2.w;
  3949. return (x * x) + (y * y) + (z * z) + (w * w);
  3950. };
  3951. /**
  3952. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3953. */
  3954. Vector4.Center = function (value1, value2) {
  3955. var center = value1.add(value2);
  3956. center.scaleInPlace(0.5);
  3957. return center;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3961. * This methods computes transformed normalized direction vectors only.
  3962. */
  3963. Vector4.TransformNormal = function (vector, transformation) {
  3964. var result = Vector4.Zero();
  3965. Vector4.TransformNormalToRef(vector, transformation, result);
  3966. return result;
  3967. };
  3968. /**
  3969. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3970. * This methods computes transformed normalized direction vectors only.
  3971. */
  3972. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3973. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3974. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3975. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3976. result.x = x;
  3977. result.y = y;
  3978. result.z = z;
  3979. result.w = vector.w;
  3980. };
  3981. /**
  3982. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3983. * This methods computes transformed normalized direction vectors only.
  3984. */
  3985. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3986. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3987. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3988. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3989. result.w = w;
  3990. };
  3991. return Vector4;
  3992. }());
  3993. BABYLON.Vector4 = Vector4;
  3994. var Size = /** @class */ (function () {
  3995. /**
  3996. * Creates a Size object from the passed width and height (floats).
  3997. */
  3998. function Size(width, height) {
  3999. this.width = width;
  4000. this.height = height;
  4001. }
  4002. // Returns a string with the Size width and height.
  4003. Size.prototype.toString = function () {
  4004. return "{W: " + this.width + ", H: " + this.height + "}";
  4005. };
  4006. /**
  4007. * Returns the string "Size"
  4008. */
  4009. Size.prototype.getClassName = function () {
  4010. return "Size";
  4011. };
  4012. /**
  4013. * Returns the Size hash code.
  4014. */
  4015. Size.prototype.getHashCode = function () {
  4016. var hash = this.width || 0;
  4017. hash = (hash * 397) ^ (this.height || 0);
  4018. return hash;
  4019. };
  4020. /**
  4021. * Updates the current size from the passed one.
  4022. * Returns the updated Size.
  4023. */
  4024. Size.prototype.copyFrom = function (src) {
  4025. this.width = src.width;
  4026. this.height = src.height;
  4027. };
  4028. /**
  4029. * Updates in place the current Size from the passed floats.
  4030. * Returns the updated Size.
  4031. */
  4032. Size.prototype.copyFromFloats = function (width, height) {
  4033. this.width = width;
  4034. this.height = height;
  4035. return this;
  4036. };
  4037. /**
  4038. * Updates in place the current Size from the passed floats.
  4039. * Returns the updated Size.
  4040. */
  4041. Size.prototype.set = function (width, height) {
  4042. return this.copyFromFloats(width, height);
  4043. };
  4044. /**
  4045. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4046. */
  4047. Size.prototype.multiplyByFloats = function (w, h) {
  4048. return new Size(this.width * w, this.height * h);
  4049. };
  4050. /**
  4051. * Returns a new Size copied from the passed one.
  4052. */
  4053. Size.prototype.clone = function () {
  4054. return new Size(this.width, this.height);
  4055. };
  4056. /**
  4057. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4058. */
  4059. Size.prototype.equals = function (other) {
  4060. if (!other) {
  4061. return false;
  4062. }
  4063. return (this.width === other.width) && (this.height === other.height);
  4064. };
  4065. Object.defineProperty(Size.prototype, "surface", {
  4066. /**
  4067. * Returns the surface of the Size : width * height (float).
  4068. */
  4069. get: function () {
  4070. return this.width * this.height;
  4071. },
  4072. enumerable: true,
  4073. configurable: true
  4074. });
  4075. /**
  4076. * Returns a new Size set to (0.0, 0.0)
  4077. */
  4078. Size.Zero = function () {
  4079. return new Size(0.0, 0.0);
  4080. };
  4081. /**
  4082. * Returns a new Size set as the addition result of the current Size and the passed one.
  4083. */
  4084. Size.prototype.add = function (otherSize) {
  4085. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4086. return r;
  4087. };
  4088. /**
  4089. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4090. */
  4091. Size.prototype.subtract = function (otherSize) {
  4092. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4093. return r;
  4094. };
  4095. /**
  4096. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4097. */
  4098. Size.Lerp = function (start, end, amount) {
  4099. var w = start.width + ((end.width - start.width) * amount);
  4100. var h = start.height + ((end.height - start.height) * amount);
  4101. return new Size(w, h);
  4102. };
  4103. return Size;
  4104. }());
  4105. BABYLON.Size = Size;
  4106. var Quaternion = /** @class */ (function () {
  4107. /**
  4108. * Creates a new Quaternion from the passed floats.
  4109. */
  4110. function Quaternion(x, y, z, w) {
  4111. if (x === void 0) { x = 0.0; }
  4112. if (y === void 0) { y = 0.0; }
  4113. if (z === void 0) { z = 0.0; }
  4114. if (w === void 0) { w = 1.0; }
  4115. this.x = x;
  4116. this.y = y;
  4117. this.z = z;
  4118. this.w = w;
  4119. }
  4120. /**
  4121. * Returns a string with the Quaternion coordinates.
  4122. */
  4123. Quaternion.prototype.toString = function () {
  4124. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4125. };
  4126. /**
  4127. * Returns the string "Quaternion".
  4128. */
  4129. Quaternion.prototype.getClassName = function () {
  4130. return "Quaternion";
  4131. };
  4132. /**
  4133. * Returns the Quaternion hash code.
  4134. */
  4135. Quaternion.prototype.getHashCode = function () {
  4136. var hash = this.x || 0;
  4137. hash = (hash * 397) ^ (this.y || 0);
  4138. hash = (hash * 397) ^ (this.z || 0);
  4139. hash = (hash * 397) ^ (this.w || 0);
  4140. return hash;
  4141. };
  4142. /**
  4143. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4144. */
  4145. Quaternion.prototype.asArray = function () {
  4146. return [this.x, this.y, this.z, this.w];
  4147. };
  4148. /**
  4149. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4150. */
  4151. Quaternion.prototype.equals = function (otherQuaternion) {
  4152. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4153. };
  4154. /**
  4155. * Returns a new Quaternion copied from the current one.
  4156. */
  4157. Quaternion.prototype.clone = function () {
  4158. return new Quaternion(this.x, this.y, this.z, this.w);
  4159. };
  4160. /**
  4161. * Updates the current Quaternion from the passed one coordinates.
  4162. * Returns the updated Quaterion.
  4163. */
  4164. Quaternion.prototype.copyFrom = function (other) {
  4165. this.x = other.x;
  4166. this.y = other.y;
  4167. this.z = other.z;
  4168. this.w = other.w;
  4169. return this;
  4170. };
  4171. /**
  4172. * Updates the current Quaternion from the passed float coordinates.
  4173. * Returns the updated Quaterion.
  4174. */
  4175. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4176. this.x = x;
  4177. this.y = y;
  4178. this.z = z;
  4179. this.w = w;
  4180. return this;
  4181. };
  4182. /**
  4183. * Updates the current Quaternion from the passed float coordinates.
  4184. * Returns the updated Quaterion.
  4185. */
  4186. Quaternion.prototype.set = function (x, y, z, w) {
  4187. return this.copyFromFloats(x, y, z, w);
  4188. };
  4189. /**
  4190. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4191. */
  4192. Quaternion.prototype.add = function (other) {
  4193. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4194. };
  4195. /**
  4196. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4197. */
  4198. Quaternion.prototype.subtract = function (other) {
  4199. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4200. };
  4201. /**
  4202. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4203. */
  4204. Quaternion.prototype.scale = function (value) {
  4205. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4206. };
  4207. /**
  4208. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4209. */
  4210. Quaternion.prototype.multiply = function (q1) {
  4211. var result = new Quaternion(0, 0, 0, 1.0);
  4212. this.multiplyToRef(q1, result);
  4213. return result;
  4214. };
  4215. /**
  4216. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4217. * Returns the current Quaternion.
  4218. */
  4219. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4220. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4221. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4222. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4223. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4224. result.copyFromFloats(x, y, z, w);
  4225. return this;
  4226. };
  4227. /**
  4228. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4229. * Returns the updated Quaternion.
  4230. */
  4231. Quaternion.prototype.multiplyInPlace = function (q1) {
  4232. this.multiplyToRef(q1, this);
  4233. return this;
  4234. };
  4235. /**
  4236. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4237. * Returns the current Quaternion.
  4238. */
  4239. Quaternion.prototype.conjugateToRef = function (ref) {
  4240. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4241. return this;
  4242. };
  4243. /**
  4244. * Conjugates in place the current Quaternion.
  4245. * Returns the updated Quaternion.
  4246. */
  4247. Quaternion.prototype.conjugateInPlace = function () {
  4248. this.x *= -1;
  4249. this.y *= -1;
  4250. this.z *= -1;
  4251. return this;
  4252. };
  4253. /**
  4254. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4255. */
  4256. Quaternion.prototype.conjugate = function () {
  4257. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4258. return result;
  4259. };
  4260. /**
  4261. * Returns the Quaternion length (float).
  4262. */
  4263. Quaternion.prototype.length = function () {
  4264. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4265. };
  4266. /**
  4267. * Normalize in place the current Quaternion.
  4268. * Returns the updated Quaternion.
  4269. */
  4270. Quaternion.prototype.normalize = function () {
  4271. var length = 1.0 / this.length();
  4272. this.x *= length;
  4273. this.y *= length;
  4274. this.z *= length;
  4275. this.w *= length;
  4276. return this;
  4277. };
  4278. /**
  4279. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4280. */
  4281. Quaternion.prototype.toEulerAngles = function (order) {
  4282. if (order === void 0) { order = "YZX"; }
  4283. var result = Vector3.Zero();
  4284. this.toEulerAnglesToRef(result, order);
  4285. return result;
  4286. };
  4287. /**
  4288. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4289. * Returns the current Quaternion.
  4290. */
  4291. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4292. if (order === void 0) { order = "YZX"; }
  4293. var qz = this.z;
  4294. var qx = this.x;
  4295. var qy = this.y;
  4296. var qw = this.w;
  4297. var sqw = qw * qw;
  4298. var sqz = qz * qz;
  4299. var sqx = qx * qx;
  4300. var sqy = qy * qy;
  4301. var zAxisY = qy * qz - qx * qw;
  4302. var limit = .4999999;
  4303. if (zAxisY < -limit) {
  4304. result.y = 2 * Math.atan2(qy, qw);
  4305. result.x = Math.PI / 2;
  4306. result.z = 0;
  4307. }
  4308. else if (zAxisY > limit) {
  4309. result.y = 2 * Math.atan2(qy, qw);
  4310. result.x = -Math.PI / 2;
  4311. result.z = 0;
  4312. }
  4313. else {
  4314. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4315. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4316. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4317. }
  4318. return this;
  4319. };
  4320. /**
  4321. * Updates the passed rotation matrix with the current Quaternion values.
  4322. * Returns the current Quaternion.
  4323. */
  4324. Quaternion.prototype.toRotationMatrix = function (result) {
  4325. var xx = this.x * this.x;
  4326. var yy = this.y * this.y;
  4327. var zz = this.z * this.z;
  4328. var xy = this.x * this.y;
  4329. var zw = this.z * this.w;
  4330. var zx = this.z * this.x;
  4331. var yw = this.y * this.w;
  4332. var yz = this.y * this.z;
  4333. var xw = this.x * this.w;
  4334. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4335. result.m[1] = 2.0 * (xy + zw);
  4336. result.m[2] = 2.0 * (zx - yw);
  4337. result.m[3] = 0;
  4338. result.m[4] = 2.0 * (xy - zw);
  4339. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4340. result.m[6] = 2.0 * (yz + xw);
  4341. result.m[7] = 0;
  4342. result.m[8] = 2.0 * (zx + yw);
  4343. result.m[9] = 2.0 * (yz - xw);
  4344. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4345. result.m[11] = 0;
  4346. result.m[12] = 0;
  4347. result.m[13] = 0;
  4348. result.m[14] = 0;
  4349. result.m[15] = 1.0;
  4350. result._markAsUpdated();
  4351. return this;
  4352. };
  4353. /**
  4354. * Updates the current Quaternion from the passed rotation matrix values.
  4355. * Returns the updated Quaternion.
  4356. */
  4357. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4358. Quaternion.FromRotationMatrixToRef(matrix, this);
  4359. return this;
  4360. };
  4361. // Statics
  4362. /**
  4363. * Returns a new Quaternion set from the passed rotation matrix values.
  4364. */
  4365. Quaternion.FromRotationMatrix = function (matrix) {
  4366. var result = new Quaternion();
  4367. Quaternion.FromRotationMatrixToRef(matrix, result);
  4368. return result;
  4369. };
  4370. /**
  4371. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4372. */
  4373. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4374. var data = matrix.m;
  4375. var m11 = data[0], m12 = data[4], m13 = data[8];
  4376. var m21 = data[1], m22 = data[5], m23 = data[9];
  4377. var m31 = data[2], m32 = data[6], m33 = data[10];
  4378. var trace = m11 + m22 + m33;
  4379. var s;
  4380. if (trace > 0) {
  4381. s = 0.5 / Math.sqrt(trace + 1.0);
  4382. result.w = 0.25 / s;
  4383. result.x = (m32 - m23) * s;
  4384. result.y = (m13 - m31) * s;
  4385. result.z = (m21 - m12) * s;
  4386. }
  4387. else if (m11 > m22 && m11 > m33) {
  4388. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4389. result.w = (m32 - m23) / s;
  4390. result.x = 0.25 * s;
  4391. result.y = (m12 + m21) / s;
  4392. result.z = (m13 + m31) / s;
  4393. }
  4394. else if (m22 > m33) {
  4395. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4396. result.w = (m13 - m31) / s;
  4397. result.x = (m12 + m21) / s;
  4398. result.y = 0.25 * s;
  4399. result.z = (m23 + m32) / s;
  4400. }
  4401. else {
  4402. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4403. result.w = (m21 - m12) / s;
  4404. result.x = (m13 + m31) / s;
  4405. result.y = (m23 + m32) / s;
  4406. result.z = 0.25 * s;
  4407. }
  4408. };
  4409. /**
  4410. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4411. */
  4412. Quaternion.Zero = function () {
  4413. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4414. };
  4415. /**
  4416. * Returns a new Quaternion as the inverted current Quaternion.
  4417. */
  4418. Quaternion.Inverse = function (q) {
  4419. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4420. };
  4421. /**
  4422. * Returns the identity Quaternion.
  4423. */
  4424. Quaternion.Identity = function () {
  4425. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4426. };
  4427. Quaternion.IsIdentity = function (quaternion) {
  4428. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4429. };
  4430. /**
  4431. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4432. */
  4433. Quaternion.RotationAxis = function (axis, angle) {
  4434. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4435. };
  4436. /**
  4437. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4438. */
  4439. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4440. var sin = Math.sin(angle / 2);
  4441. axis.normalize();
  4442. result.w = Math.cos(angle / 2);
  4443. result.x = axis.x * sin;
  4444. result.y = axis.y * sin;
  4445. result.z = axis.z * sin;
  4446. return result;
  4447. };
  4448. /**
  4449. * Retuns a new Quaternion set from the starting index of the passed array.
  4450. */
  4451. Quaternion.FromArray = function (array, offset) {
  4452. if (!offset) {
  4453. offset = 0;
  4454. }
  4455. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4456. };
  4457. /**
  4458. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4459. */
  4460. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4461. var q = new Quaternion();
  4462. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4463. return q;
  4464. };
  4465. /**
  4466. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4467. */
  4468. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4469. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4470. var halfRoll = roll * 0.5;
  4471. var halfPitch = pitch * 0.5;
  4472. var halfYaw = yaw * 0.5;
  4473. var sinRoll = Math.sin(halfRoll);
  4474. var cosRoll = Math.cos(halfRoll);
  4475. var sinPitch = Math.sin(halfPitch);
  4476. var cosPitch = Math.cos(halfPitch);
  4477. var sinYaw = Math.sin(halfYaw);
  4478. var cosYaw = Math.cos(halfYaw);
  4479. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4480. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4481. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4482. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4483. };
  4484. /**
  4485. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4486. */
  4487. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4488. var result = new Quaternion();
  4489. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4490. return result;
  4491. };
  4492. /**
  4493. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4494. */
  4495. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4496. // Produces a quaternion from Euler angles in the z-x-z orientation
  4497. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4498. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4499. var halfBeta = beta * 0.5;
  4500. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4501. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4502. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4503. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4504. };
  4505. /**
  4506. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4507. * cf to Vector3.RotationFromAxis() documentation.
  4508. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4509. */
  4510. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4511. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4512. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4513. return quat;
  4514. };
  4515. /**
  4516. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4517. * cf to Vector3.RotationFromAxis() documentation.
  4518. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4519. */
  4520. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4521. var rotMat = MathTmp.Matrix[0];
  4522. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4523. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4524. };
  4525. Quaternion.Slerp = function (left, right, amount) {
  4526. var result = Quaternion.Identity();
  4527. Quaternion.SlerpToRef(left, right, amount, result);
  4528. return result;
  4529. };
  4530. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4531. var num2;
  4532. var num3;
  4533. var num = amount;
  4534. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4535. var flag = false;
  4536. if (num4 < 0) {
  4537. flag = true;
  4538. num4 = -num4;
  4539. }
  4540. if (num4 > 0.999999) {
  4541. num3 = 1 - num;
  4542. num2 = flag ? -num : num;
  4543. }
  4544. else {
  4545. var num5 = Math.acos(num4);
  4546. var num6 = (1.0 / Math.sin(num5));
  4547. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4548. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4549. }
  4550. result.x = (num3 * left.x) + (num2 * right.x);
  4551. result.y = (num3 * left.y) + (num2 * right.y);
  4552. result.z = (num3 * left.z) + (num2 * right.z);
  4553. result.w = (num3 * left.w) + (num2 * right.w);
  4554. };
  4555. /**
  4556. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4557. */
  4558. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4559. var squared = amount * amount;
  4560. var cubed = amount * squared;
  4561. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4562. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4563. var part3 = (cubed - (2.0 * squared)) + amount;
  4564. var part4 = cubed - squared;
  4565. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4566. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4567. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4568. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4569. return new Quaternion(x, y, z, w);
  4570. };
  4571. return Quaternion;
  4572. }());
  4573. BABYLON.Quaternion = Quaternion;
  4574. var Matrix = /** @class */ (function () {
  4575. function Matrix() {
  4576. this._isIdentity = false;
  4577. this._isIdentityDirty = true;
  4578. this.m = new Float32Array(16);
  4579. this._markAsUpdated();
  4580. }
  4581. Matrix.prototype._markAsUpdated = function () {
  4582. this.updateFlag = Matrix._updateFlagSeed++;
  4583. this._isIdentityDirty = true;
  4584. };
  4585. // Properties
  4586. /**
  4587. * Boolean : True is the matrix is the identity matrix
  4588. */
  4589. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4590. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4591. if (this._isIdentityDirty) {
  4592. this._isIdentityDirty = false;
  4593. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4594. this._isIdentity = false;
  4595. }
  4596. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4597. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4598. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4599. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4600. this._isIdentity = false;
  4601. }
  4602. else {
  4603. this._isIdentity = true;
  4604. }
  4605. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4606. this._isIdentity = false;
  4607. }
  4608. }
  4609. return this._isIdentity;
  4610. };
  4611. /**
  4612. * Returns the matrix determinant (float).
  4613. */
  4614. Matrix.prototype.determinant = function () {
  4615. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4616. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4617. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4618. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4619. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4620. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4621. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4622. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4623. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4624. };
  4625. // Methods
  4626. /**
  4627. * Returns the matrix underlying array.
  4628. */
  4629. Matrix.prototype.toArray = function () {
  4630. return this.m;
  4631. };
  4632. /**
  4633. * Returns the matrix underlying array.
  4634. */
  4635. Matrix.prototype.asArray = function () {
  4636. return this.toArray();
  4637. };
  4638. /**
  4639. * Inverts in place the Matrix.
  4640. * Returns the Matrix inverted.
  4641. */
  4642. Matrix.prototype.invert = function () {
  4643. this.invertToRef(this);
  4644. return this;
  4645. };
  4646. /**
  4647. * Sets all the matrix elements to zero.
  4648. * Returns the Matrix.
  4649. */
  4650. Matrix.prototype.reset = function () {
  4651. for (var index = 0; index < 16; index++) {
  4652. this.m[index] = 0.0;
  4653. }
  4654. this._markAsUpdated();
  4655. return this;
  4656. };
  4657. /**
  4658. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4659. */
  4660. Matrix.prototype.add = function (other) {
  4661. var result = new Matrix();
  4662. this.addToRef(other, result);
  4663. return result;
  4664. };
  4665. /**
  4666. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4667. * Returns the Matrix.
  4668. */
  4669. Matrix.prototype.addToRef = function (other, result) {
  4670. for (var index = 0; index < 16; index++) {
  4671. result.m[index] = this.m[index] + other.m[index];
  4672. }
  4673. result._markAsUpdated();
  4674. return this;
  4675. };
  4676. /**
  4677. * Adds in place the passed matrix to the current Matrix.
  4678. * Returns the updated Matrix.
  4679. */
  4680. Matrix.prototype.addToSelf = function (other) {
  4681. for (var index = 0; index < 16; index++) {
  4682. this.m[index] += other.m[index];
  4683. }
  4684. this._markAsUpdated();
  4685. return this;
  4686. };
  4687. /**
  4688. * Sets the passed matrix with the current inverted Matrix.
  4689. * Returns the unmodified current Matrix.
  4690. */
  4691. Matrix.prototype.invertToRef = function (other) {
  4692. var l1 = this.m[0];
  4693. var l2 = this.m[1];
  4694. var l3 = this.m[2];
  4695. var l4 = this.m[3];
  4696. var l5 = this.m[4];
  4697. var l6 = this.m[5];
  4698. var l7 = this.m[6];
  4699. var l8 = this.m[7];
  4700. var l9 = this.m[8];
  4701. var l10 = this.m[9];
  4702. var l11 = this.m[10];
  4703. var l12 = this.m[11];
  4704. var l13 = this.m[12];
  4705. var l14 = this.m[13];
  4706. var l15 = this.m[14];
  4707. var l16 = this.m[15];
  4708. var l17 = (l11 * l16) - (l12 * l15);
  4709. var l18 = (l10 * l16) - (l12 * l14);
  4710. var l19 = (l10 * l15) - (l11 * l14);
  4711. var l20 = (l9 * l16) - (l12 * l13);
  4712. var l21 = (l9 * l15) - (l11 * l13);
  4713. var l22 = (l9 * l14) - (l10 * l13);
  4714. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4715. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4716. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4717. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4718. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4719. var l28 = (l7 * l16) - (l8 * l15);
  4720. var l29 = (l6 * l16) - (l8 * l14);
  4721. var l30 = (l6 * l15) - (l7 * l14);
  4722. var l31 = (l5 * l16) - (l8 * l13);
  4723. var l32 = (l5 * l15) - (l7 * l13);
  4724. var l33 = (l5 * l14) - (l6 * l13);
  4725. var l34 = (l7 * l12) - (l8 * l11);
  4726. var l35 = (l6 * l12) - (l8 * l10);
  4727. var l36 = (l6 * l11) - (l7 * l10);
  4728. var l37 = (l5 * l12) - (l8 * l9);
  4729. var l38 = (l5 * l11) - (l7 * l9);
  4730. var l39 = (l5 * l10) - (l6 * l9);
  4731. other.m[0] = l23 * l27;
  4732. other.m[4] = l24 * l27;
  4733. other.m[8] = l25 * l27;
  4734. other.m[12] = l26 * l27;
  4735. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4736. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4737. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4738. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4739. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4740. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4741. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4742. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4743. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4744. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4745. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4746. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4747. other._markAsUpdated();
  4748. return this;
  4749. };
  4750. /**
  4751. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4752. * Returns the updated Matrix.
  4753. */
  4754. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4755. this.m[12] = x;
  4756. this.m[13] = y;
  4757. this.m[14] = z;
  4758. this._markAsUpdated();
  4759. return this;
  4760. };
  4761. /**
  4762. * Inserts the translation vector in the current Matrix.
  4763. * Returns the updated Matrix.
  4764. */
  4765. Matrix.prototype.setTranslation = function (vector3) {
  4766. this.m[12] = vector3.x;
  4767. this.m[13] = vector3.y;
  4768. this.m[14] = vector3.z;
  4769. this._markAsUpdated();
  4770. return this;
  4771. };
  4772. /**
  4773. * Returns a new Vector3 as the extracted translation from the Matrix.
  4774. */
  4775. Matrix.prototype.getTranslation = function () {
  4776. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4777. };
  4778. /**
  4779. * Fill a Vector3 with the extracted translation from the Matrix.
  4780. */
  4781. Matrix.prototype.getTranslationToRef = function (result) {
  4782. result.x = this.m[12];
  4783. result.y = this.m[13];
  4784. result.z = this.m[14];
  4785. return this;
  4786. };
  4787. /**
  4788. * Remove rotation and scaling part from the Matrix.
  4789. * Returns the updated Matrix.
  4790. */
  4791. Matrix.prototype.removeRotationAndScaling = function () {
  4792. this.setRowFromFloats(0, 1, 0, 0, 0);
  4793. this.setRowFromFloats(1, 0, 1, 0, 0);
  4794. this.setRowFromFloats(2, 0, 0, 1, 0);
  4795. return this;
  4796. };
  4797. /**
  4798. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4799. */
  4800. Matrix.prototype.multiply = function (other) {
  4801. var result = new Matrix();
  4802. this.multiplyToRef(other, result);
  4803. return result;
  4804. };
  4805. /**
  4806. * Updates the current Matrix from the passed one values.
  4807. * Returns the updated Matrix.
  4808. */
  4809. Matrix.prototype.copyFrom = function (other) {
  4810. for (var index = 0; index < 16; index++) {
  4811. this.m[index] = other.m[index];
  4812. }
  4813. this._markAsUpdated();
  4814. return this;
  4815. };
  4816. /**
  4817. * Populates the passed array from the starting index with the Matrix values.
  4818. * Returns the Matrix.
  4819. */
  4820. Matrix.prototype.copyToArray = function (array, offset) {
  4821. if (offset === void 0) { offset = 0; }
  4822. for (var index = 0; index < 16; index++) {
  4823. array[offset + index] = this.m[index];
  4824. }
  4825. return this;
  4826. };
  4827. /**
  4828. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4829. */
  4830. Matrix.prototype.multiplyToRef = function (other, result) {
  4831. this.multiplyToArray(other, result.m, 0);
  4832. result._markAsUpdated();
  4833. return this;
  4834. };
  4835. /**
  4836. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4837. */
  4838. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4839. var tm0 = this.m[0];
  4840. var tm1 = this.m[1];
  4841. var tm2 = this.m[2];
  4842. var tm3 = this.m[3];
  4843. var tm4 = this.m[4];
  4844. var tm5 = this.m[5];
  4845. var tm6 = this.m[6];
  4846. var tm7 = this.m[7];
  4847. var tm8 = this.m[8];
  4848. var tm9 = this.m[9];
  4849. var tm10 = this.m[10];
  4850. var tm11 = this.m[11];
  4851. var tm12 = this.m[12];
  4852. var tm13 = this.m[13];
  4853. var tm14 = this.m[14];
  4854. var tm15 = this.m[15];
  4855. var om0 = other.m[0];
  4856. var om1 = other.m[1];
  4857. var om2 = other.m[2];
  4858. var om3 = other.m[3];
  4859. var om4 = other.m[4];
  4860. var om5 = other.m[5];
  4861. var om6 = other.m[6];
  4862. var om7 = other.m[7];
  4863. var om8 = other.m[8];
  4864. var om9 = other.m[9];
  4865. var om10 = other.m[10];
  4866. var om11 = other.m[11];
  4867. var om12 = other.m[12];
  4868. var om13 = other.m[13];
  4869. var om14 = other.m[14];
  4870. var om15 = other.m[15];
  4871. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4872. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4873. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4874. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4875. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4876. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4877. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4878. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4879. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4880. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4881. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4882. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4883. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4884. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4885. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4886. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4887. return this;
  4888. };
  4889. /**
  4890. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4891. */
  4892. Matrix.prototype.equals = function (value) {
  4893. return value &&
  4894. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4895. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4896. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4897. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4898. };
  4899. /**
  4900. * Returns a new Matrix from the current Matrix.
  4901. */
  4902. Matrix.prototype.clone = function () {
  4903. 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]);
  4904. };
  4905. /**
  4906. * Returns the string "Matrix"
  4907. */
  4908. Matrix.prototype.getClassName = function () {
  4909. return "Matrix";
  4910. };
  4911. /**
  4912. * Returns the Matrix hash code.
  4913. */
  4914. Matrix.prototype.getHashCode = function () {
  4915. var hash = this.m[0] || 0;
  4916. for (var i = 1; i < 16; i++) {
  4917. hash = (hash * 397) ^ (this.m[i] || 0);
  4918. }
  4919. return hash;
  4920. };
  4921. /**
  4922. * Decomposes the current Matrix into :
  4923. * - a scale vector3 passed as a reference to update,
  4924. * - a rotation quaternion passed as a reference to update,
  4925. * - a translation vector3 passed as a reference to update.
  4926. * Returns the true if operation was successful.
  4927. */
  4928. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4929. translation.x = this.m[12];
  4930. translation.y = this.m[13];
  4931. translation.z = this.m[14];
  4932. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4933. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4934. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4935. if (this.determinant() <= 0) {
  4936. scale.y *= -1;
  4937. }
  4938. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4939. rotation.x = 0;
  4940. rotation.y = 0;
  4941. rotation.z = 0;
  4942. rotation.w = 1;
  4943. return false;
  4944. }
  4945. 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]);
  4946. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4947. return true;
  4948. };
  4949. /**
  4950. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4951. */
  4952. Matrix.prototype.getRotationMatrix = function () {
  4953. var result = Matrix.Identity();
  4954. this.getRotationMatrixToRef(result);
  4955. return result;
  4956. };
  4957. /**
  4958. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4959. * Returns the current Matrix.
  4960. */
  4961. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4962. var m = this.m;
  4963. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4964. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4965. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4966. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4967. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4968. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4969. 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);
  4970. return this;
  4971. };
  4972. // Statics
  4973. /**
  4974. * Returns a new Matrix set from the starting index of the passed array.
  4975. */
  4976. Matrix.FromArray = function (array, offset) {
  4977. var result = new Matrix();
  4978. if (!offset) {
  4979. offset = 0;
  4980. }
  4981. Matrix.FromArrayToRef(array, offset, result);
  4982. return result;
  4983. };
  4984. /**
  4985. * Sets the passed "result" matrix from the starting index of the passed array.
  4986. */
  4987. Matrix.FromArrayToRef = function (array, offset, result) {
  4988. for (var index = 0; index < 16; index++) {
  4989. result.m[index] = array[index + offset];
  4990. }
  4991. result._markAsUpdated();
  4992. };
  4993. /**
  4994. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4995. */
  4996. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4997. for (var index = 0; index < 16; index++) {
  4998. result.m[index] = array[index + offset] * scale;
  4999. }
  5000. result._markAsUpdated();
  5001. };
  5002. /**
  5003. * Sets the passed matrix "result" with the 16 passed floats.
  5004. */
  5005. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5006. result.m[0] = initialM11;
  5007. result.m[1] = initialM12;
  5008. result.m[2] = initialM13;
  5009. result.m[3] = initialM14;
  5010. result.m[4] = initialM21;
  5011. result.m[5] = initialM22;
  5012. result.m[6] = initialM23;
  5013. result.m[7] = initialM24;
  5014. result.m[8] = initialM31;
  5015. result.m[9] = initialM32;
  5016. result.m[10] = initialM33;
  5017. result.m[11] = initialM34;
  5018. result.m[12] = initialM41;
  5019. result.m[13] = initialM42;
  5020. result.m[14] = initialM43;
  5021. result.m[15] = initialM44;
  5022. result._markAsUpdated();
  5023. };
  5024. /**
  5025. * Returns the index-th row of the current matrix as a new Vector4.
  5026. */
  5027. Matrix.prototype.getRow = function (index) {
  5028. if (index < 0 || index > 3) {
  5029. return null;
  5030. }
  5031. var i = index * 4;
  5032. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5033. };
  5034. /**
  5035. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5036. * Returns the updated Matrix.
  5037. */
  5038. Matrix.prototype.setRow = function (index, row) {
  5039. if (index < 0 || index > 3) {
  5040. return this;
  5041. }
  5042. var i = index * 4;
  5043. this.m[i + 0] = row.x;
  5044. this.m[i + 1] = row.y;
  5045. this.m[i + 2] = row.z;
  5046. this.m[i + 3] = row.w;
  5047. this._markAsUpdated();
  5048. return this;
  5049. };
  5050. /**
  5051. * Compute the transpose of the matrix.
  5052. * Returns a new Matrix.
  5053. */
  5054. Matrix.prototype.transpose = function () {
  5055. return Matrix.Transpose(this);
  5056. };
  5057. /**
  5058. * Compute the transpose of the matrix.
  5059. * Returns the current matrix.
  5060. */
  5061. Matrix.prototype.transposeToRef = function (result) {
  5062. Matrix.TransposeToRef(this, result);
  5063. return this;
  5064. };
  5065. /**
  5066. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5067. * Returns the updated Matrix.
  5068. */
  5069. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5070. if (index < 0 || index > 3) {
  5071. return this;
  5072. }
  5073. var i = index * 4;
  5074. this.m[i + 0] = x;
  5075. this.m[i + 1] = y;
  5076. this.m[i + 2] = z;
  5077. this.m[i + 3] = w;
  5078. this._markAsUpdated();
  5079. return this;
  5080. };
  5081. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5082. /**
  5083. * Static identity matrix to be used as readonly matrix
  5084. * Must not be updated.
  5085. */
  5086. get: function () {
  5087. return Matrix._identityReadOnly;
  5088. },
  5089. enumerable: true,
  5090. configurable: true
  5091. });
  5092. /**
  5093. * Returns a new Matrix set from the 16 passed floats.
  5094. */
  5095. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5096. var result = new Matrix();
  5097. result.m[0] = initialM11;
  5098. result.m[1] = initialM12;
  5099. result.m[2] = initialM13;
  5100. result.m[3] = initialM14;
  5101. result.m[4] = initialM21;
  5102. result.m[5] = initialM22;
  5103. result.m[6] = initialM23;
  5104. result.m[7] = initialM24;
  5105. result.m[8] = initialM31;
  5106. result.m[9] = initialM32;
  5107. result.m[10] = initialM33;
  5108. result.m[11] = initialM34;
  5109. result.m[12] = initialM41;
  5110. result.m[13] = initialM42;
  5111. result.m[14] = initialM43;
  5112. result.m[15] = initialM44;
  5113. return result;
  5114. };
  5115. /**
  5116. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5117. */
  5118. Matrix.Compose = function (scale, rotation, translation) {
  5119. var result = Matrix.Identity();
  5120. Matrix.ComposeToRef(scale, rotation, translation, result);
  5121. return result;
  5122. };
  5123. /**
  5124. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5125. */
  5126. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5127. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5128. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5129. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5130. result.setTranslation(translation);
  5131. };
  5132. /**
  5133. * Returns a new indentity Matrix.
  5134. */
  5135. Matrix.Identity = function () {
  5136. 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);
  5137. };
  5138. /**
  5139. * Sets the passed "result" as an identity matrix.
  5140. */
  5141. Matrix.IdentityToRef = function (result) {
  5142. 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);
  5143. };
  5144. /**
  5145. * Returns a new zero Matrix.
  5146. */
  5147. Matrix.Zero = function () {
  5148. 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);
  5149. };
  5150. /**
  5151. * Returns a new rotation matrix for "angle" radians around the X axis.
  5152. */
  5153. Matrix.RotationX = function (angle) {
  5154. var result = new Matrix();
  5155. Matrix.RotationXToRef(angle, result);
  5156. return result;
  5157. };
  5158. /**
  5159. * Returns a new Matrix as the passed inverted one.
  5160. */
  5161. Matrix.Invert = function (source) {
  5162. var result = new Matrix();
  5163. source.invertToRef(result);
  5164. return result;
  5165. };
  5166. /**
  5167. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5168. */
  5169. Matrix.RotationXToRef = function (angle, result) {
  5170. var s = Math.sin(angle);
  5171. var c = Math.cos(angle);
  5172. result.m[0] = 1.0;
  5173. result.m[15] = 1.0;
  5174. result.m[5] = c;
  5175. result.m[10] = c;
  5176. result.m[9] = -s;
  5177. result.m[6] = s;
  5178. result.m[1] = 0.0;
  5179. result.m[2] = 0.0;
  5180. result.m[3] = 0.0;
  5181. result.m[4] = 0.0;
  5182. result.m[7] = 0.0;
  5183. result.m[8] = 0.0;
  5184. result.m[11] = 0.0;
  5185. result.m[12] = 0.0;
  5186. result.m[13] = 0.0;
  5187. result.m[14] = 0.0;
  5188. result._markAsUpdated();
  5189. };
  5190. /**
  5191. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5192. */
  5193. Matrix.RotationY = function (angle) {
  5194. var result = new Matrix();
  5195. Matrix.RotationYToRef(angle, result);
  5196. return result;
  5197. };
  5198. /**
  5199. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5200. */
  5201. Matrix.RotationYToRef = function (angle, result) {
  5202. var s = Math.sin(angle);
  5203. var c = Math.cos(angle);
  5204. result.m[5] = 1.0;
  5205. result.m[15] = 1.0;
  5206. result.m[0] = c;
  5207. result.m[2] = -s;
  5208. result.m[8] = s;
  5209. result.m[10] = c;
  5210. result.m[1] = 0.0;
  5211. result.m[3] = 0.0;
  5212. result.m[4] = 0.0;
  5213. result.m[6] = 0.0;
  5214. result.m[7] = 0.0;
  5215. result.m[9] = 0.0;
  5216. result.m[11] = 0.0;
  5217. result.m[12] = 0.0;
  5218. result.m[13] = 0.0;
  5219. result.m[14] = 0.0;
  5220. result._markAsUpdated();
  5221. };
  5222. /**
  5223. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5224. */
  5225. Matrix.RotationZ = function (angle) {
  5226. var result = new Matrix();
  5227. Matrix.RotationZToRef(angle, result);
  5228. return result;
  5229. };
  5230. /**
  5231. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5232. */
  5233. Matrix.RotationZToRef = function (angle, result) {
  5234. var s = Math.sin(angle);
  5235. var c = Math.cos(angle);
  5236. result.m[10] = 1.0;
  5237. result.m[15] = 1.0;
  5238. result.m[0] = c;
  5239. result.m[1] = s;
  5240. result.m[4] = -s;
  5241. result.m[5] = c;
  5242. result.m[2] = 0.0;
  5243. result.m[3] = 0.0;
  5244. result.m[6] = 0.0;
  5245. result.m[7] = 0.0;
  5246. result.m[8] = 0.0;
  5247. result.m[9] = 0.0;
  5248. result.m[11] = 0.0;
  5249. result.m[12] = 0.0;
  5250. result.m[13] = 0.0;
  5251. result.m[14] = 0.0;
  5252. result._markAsUpdated();
  5253. };
  5254. /**
  5255. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5256. */
  5257. Matrix.RotationAxis = function (axis, angle) {
  5258. var result = Matrix.Zero();
  5259. Matrix.RotationAxisToRef(axis, angle, result);
  5260. return result;
  5261. };
  5262. /**
  5263. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5264. */
  5265. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5266. var s = Math.sin(-angle);
  5267. var c = Math.cos(-angle);
  5268. var c1 = 1 - c;
  5269. axis.normalize();
  5270. result.m[0] = (axis.x * axis.x) * c1 + c;
  5271. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5272. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5273. result.m[3] = 0.0;
  5274. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5275. result.m[5] = (axis.y * axis.y) * c1 + c;
  5276. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5277. result.m[7] = 0.0;
  5278. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5279. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5280. result.m[10] = (axis.z * axis.z) * c1 + c;
  5281. result.m[11] = 0.0;
  5282. result.m[15] = 1.0;
  5283. result._markAsUpdated();
  5284. };
  5285. /**
  5286. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5287. */
  5288. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5289. var result = new Matrix();
  5290. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5291. return result;
  5292. };
  5293. /**
  5294. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5295. */
  5296. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5297. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5298. this._tempQuaternion.toRotationMatrix(result);
  5299. };
  5300. /**
  5301. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5302. */
  5303. Matrix.Scaling = function (x, y, z) {
  5304. var result = Matrix.Zero();
  5305. Matrix.ScalingToRef(x, y, z, result);
  5306. return result;
  5307. };
  5308. /**
  5309. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5310. */
  5311. Matrix.ScalingToRef = function (x, y, z, result) {
  5312. result.m[0] = x;
  5313. result.m[1] = 0.0;
  5314. result.m[2] = 0.0;
  5315. result.m[3] = 0.0;
  5316. result.m[4] = 0.0;
  5317. result.m[5] = y;
  5318. result.m[6] = 0.0;
  5319. result.m[7] = 0.0;
  5320. result.m[8] = 0.0;
  5321. result.m[9] = 0.0;
  5322. result.m[10] = z;
  5323. result.m[11] = 0.0;
  5324. result.m[12] = 0.0;
  5325. result.m[13] = 0.0;
  5326. result.m[14] = 0.0;
  5327. result.m[15] = 1.0;
  5328. result._markAsUpdated();
  5329. };
  5330. /**
  5331. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5332. */
  5333. Matrix.Translation = function (x, y, z) {
  5334. var result = Matrix.Identity();
  5335. Matrix.TranslationToRef(x, y, z, result);
  5336. return result;
  5337. };
  5338. /**
  5339. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5340. */
  5341. Matrix.TranslationToRef = function (x, y, z, result) {
  5342. 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);
  5343. };
  5344. /**
  5345. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5346. */
  5347. Matrix.Lerp = function (startValue, endValue, gradient) {
  5348. var result = Matrix.Zero();
  5349. for (var index = 0; index < 16; index++) {
  5350. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5351. }
  5352. result._markAsUpdated();
  5353. return result;
  5354. };
  5355. /**
  5356. * Returns a new Matrix whose values are computed by :
  5357. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5358. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5359. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5360. */
  5361. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5362. var startScale = new Vector3(0, 0, 0);
  5363. var startRotation = new Quaternion();
  5364. var startTranslation = new Vector3(0, 0, 0);
  5365. startValue.decompose(startScale, startRotation, startTranslation);
  5366. var endScale = new Vector3(0, 0, 0);
  5367. var endRotation = new Quaternion();
  5368. var endTranslation = new Vector3(0, 0, 0);
  5369. endValue.decompose(endScale, endRotation, endTranslation);
  5370. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5371. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5372. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5373. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5374. };
  5375. /**
  5376. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5377. * This methods works for a Left-Handed system.
  5378. */
  5379. Matrix.LookAtLH = function (eye, target, up) {
  5380. var result = Matrix.Zero();
  5381. Matrix.LookAtLHToRef(eye, target, up, result);
  5382. return result;
  5383. };
  5384. /**
  5385. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5386. * This methods works for a Left-Handed system.
  5387. */
  5388. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5389. // Z axis
  5390. target.subtractToRef(eye, this._zAxis);
  5391. this._zAxis.normalize();
  5392. // X axis
  5393. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5394. if (this._xAxis.lengthSquared() === 0) {
  5395. this._xAxis.x = 1.0;
  5396. }
  5397. else {
  5398. this._xAxis.normalize();
  5399. }
  5400. // Y axis
  5401. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5402. this._yAxis.normalize();
  5403. // Eye angles
  5404. var ex = -Vector3.Dot(this._xAxis, eye);
  5405. var ey = -Vector3.Dot(this._yAxis, eye);
  5406. var ez = -Vector3.Dot(this._zAxis, eye);
  5407. 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);
  5408. };
  5409. /**
  5410. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5411. * This methods works for a Right-Handed system.
  5412. */
  5413. Matrix.LookAtRH = function (eye, target, up) {
  5414. var result = Matrix.Zero();
  5415. Matrix.LookAtRHToRef(eye, target, up, result);
  5416. return result;
  5417. };
  5418. /**
  5419. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5420. * This methods works for a Left-Handed system.
  5421. */
  5422. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5423. // Z axis
  5424. eye.subtractToRef(target, this._zAxis);
  5425. this._zAxis.normalize();
  5426. // X axis
  5427. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5428. if (this._xAxis.lengthSquared() === 0) {
  5429. this._xAxis.x = 1.0;
  5430. }
  5431. else {
  5432. this._xAxis.normalize();
  5433. }
  5434. // Y axis
  5435. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5436. this._yAxis.normalize();
  5437. // Eye angles
  5438. var ex = -Vector3.Dot(this._xAxis, eye);
  5439. var ey = -Vector3.Dot(this._yAxis, eye);
  5440. var ez = -Vector3.Dot(this._zAxis, eye);
  5441. 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);
  5442. };
  5443. /**
  5444. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5445. */
  5446. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5447. var matrix = Matrix.Zero();
  5448. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5449. return matrix;
  5450. };
  5451. /**
  5452. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5453. */
  5454. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5455. var n = znear;
  5456. var f = zfar;
  5457. var a = 2.0 / width;
  5458. var b = 2.0 / height;
  5459. var c = 2.0 / (f - n);
  5460. var d = -(f + n) / (f - n);
  5461. 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);
  5462. };
  5463. /**
  5464. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5465. */
  5466. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5467. var matrix = Matrix.Zero();
  5468. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5469. return matrix;
  5470. };
  5471. /**
  5472. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5473. */
  5474. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5475. var n = znear;
  5476. var f = zfar;
  5477. var a = 2.0 / (right - left);
  5478. var b = 2.0 / (top - bottom);
  5479. var c = 2.0 / (f - n);
  5480. var d = -(f + n) / (f - n);
  5481. var i0 = (left + right) / (left - right);
  5482. var i1 = (top + bottom) / (bottom - top);
  5483. 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);
  5484. };
  5485. /**
  5486. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5487. */
  5488. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5489. var matrix = Matrix.Zero();
  5490. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5491. return matrix;
  5492. };
  5493. /**
  5494. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5495. */
  5496. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5497. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5498. result.m[10] *= -1.0;
  5499. };
  5500. /**
  5501. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5502. */
  5503. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5504. var matrix = Matrix.Zero();
  5505. var n = znear;
  5506. var f = zfar;
  5507. var a = 2.0 * n / width;
  5508. var b = 2.0 * n / height;
  5509. var c = (f + n) / (f - n);
  5510. var d = -2.0 * f * n / (f - n);
  5511. 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);
  5512. return matrix;
  5513. };
  5514. /**
  5515. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5516. */
  5517. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5518. var matrix = Matrix.Zero();
  5519. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5520. return matrix;
  5521. };
  5522. /**
  5523. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5524. */
  5525. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5526. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5527. var n = znear;
  5528. var f = zfar;
  5529. var t = 1.0 / (Math.tan(fov * 0.5));
  5530. var a = isVerticalFovFixed ? (t / aspect) : t;
  5531. var b = isVerticalFovFixed ? t : (t * aspect);
  5532. var c = (f + n) / (f - n);
  5533. var d = -2.0 * f * n / (f - n);
  5534. 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);
  5535. };
  5536. /**
  5537. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5538. */
  5539. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5540. var matrix = Matrix.Zero();
  5541. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5542. return matrix;
  5543. };
  5544. /**
  5545. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5546. */
  5547. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5548. //alternatively this could be expressed as:
  5549. // m = PerspectiveFovLHToRef
  5550. // m[10] *= -1.0;
  5551. // m[11] *= -1.0;
  5552. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5553. var n = znear;
  5554. var f = zfar;
  5555. var t = 1.0 / (Math.tan(fov * 0.5));
  5556. var a = isVerticalFovFixed ? (t / aspect) : t;
  5557. var b = isVerticalFovFixed ? t : (t * aspect);
  5558. var c = -(f + n) / (f - n);
  5559. var d = -2 * f * n / (f - n);
  5560. 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);
  5561. };
  5562. /**
  5563. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5564. */
  5565. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5566. if (rightHanded === void 0) { rightHanded = false; }
  5567. var rightHandedFactor = rightHanded ? -1 : 1;
  5568. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5569. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5570. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5571. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5572. var xScale = 2.0 / (leftTan + rightTan);
  5573. var yScale = 2.0 / (upTan + downTan);
  5574. result.m[0] = xScale;
  5575. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5576. result.m[5] = yScale;
  5577. result.m[6] = result.m[7] = 0.0;
  5578. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5579. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5580. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5581. result.m[10] = -zfar / (znear - zfar);
  5582. result.m[11] = 1.0 * rightHandedFactor;
  5583. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5584. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5585. // result.m[14] = (znear * zfar) / (znear - zfar);
  5586. result._markAsUpdated();
  5587. };
  5588. /**
  5589. * Returns the final transformation matrix : world * view * projection * viewport
  5590. */
  5591. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5592. var cw = viewport.width;
  5593. var ch = viewport.height;
  5594. var cx = viewport.x;
  5595. var cy = viewport.y;
  5596. 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);
  5597. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5598. };
  5599. /**
  5600. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5601. */
  5602. Matrix.GetAsMatrix2x2 = function (matrix) {
  5603. return new Float32Array([
  5604. matrix.m[0], matrix.m[1],
  5605. matrix.m[4], matrix.m[5]
  5606. ]);
  5607. };
  5608. /**
  5609. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5610. */
  5611. Matrix.GetAsMatrix3x3 = function (matrix) {
  5612. return new Float32Array([
  5613. matrix.m[0], matrix.m[1], matrix.m[2],
  5614. matrix.m[4], matrix.m[5], matrix.m[6],
  5615. matrix.m[8], matrix.m[9], matrix.m[10]
  5616. ]);
  5617. };
  5618. /**
  5619. * Compute the transpose of the passed Matrix.
  5620. * Returns a new Matrix.
  5621. */
  5622. Matrix.Transpose = function (matrix) {
  5623. var result = new Matrix();
  5624. Matrix.TransposeToRef(matrix, result);
  5625. return result;
  5626. };
  5627. /**
  5628. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5629. */
  5630. Matrix.TransposeToRef = function (matrix, result) {
  5631. result.m[0] = matrix.m[0];
  5632. result.m[1] = matrix.m[4];
  5633. result.m[2] = matrix.m[8];
  5634. result.m[3] = matrix.m[12];
  5635. result.m[4] = matrix.m[1];
  5636. result.m[5] = matrix.m[5];
  5637. result.m[6] = matrix.m[9];
  5638. result.m[7] = matrix.m[13];
  5639. result.m[8] = matrix.m[2];
  5640. result.m[9] = matrix.m[6];
  5641. result.m[10] = matrix.m[10];
  5642. result.m[11] = matrix.m[14];
  5643. result.m[12] = matrix.m[3];
  5644. result.m[13] = matrix.m[7];
  5645. result.m[14] = matrix.m[11];
  5646. result.m[15] = matrix.m[15];
  5647. };
  5648. /**
  5649. * Returns a new Matrix as the reflection matrix across the passed plane.
  5650. */
  5651. Matrix.Reflection = function (plane) {
  5652. var matrix = new Matrix();
  5653. Matrix.ReflectionToRef(plane, matrix);
  5654. return matrix;
  5655. };
  5656. /**
  5657. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5658. */
  5659. Matrix.ReflectionToRef = function (plane, result) {
  5660. plane.normalize();
  5661. var x = plane.normal.x;
  5662. var y = plane.normal.y;
  5663. var z = plane.normal.z;
  5664. var temp = -2 * x;
  5665. var temp2 = -2 * y;
  5666. var temp3 = -2 * z;
  5667. result.m[0] = (temp * x) + 1;
  5668. result.m[1] = temp2 * x;
  5669. result.m[2] = temp3 * x;
  5670. result.m[3] = 0.0;
  5671. result.m[4] = temp * y;
  5672. result.m[5] = (temp2 * y) + 1;
  5673. result.m[6] = temp3 * y;
  5674. result.m[7] = 0.0;
  5675. result.m[8] = temp * z;
  5676. result.m[9] = temp2 * z;
  5677. result.m[10] = (temp3 * z) + 1;
  5678. result.m[11] = 0.0;
  5679. result.m[12] = temp * plane.d;
  5680. result.m[13] = temp2 * plane.d;
  5681. result.m[14] = temp3 * plane.d;
  5682. result.m[15] = 1.0;
  5683. result._markAsUpdated();
  5684. };
  5685. /**
  5686. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5687. */
  5688. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5689. result.m[0] = xaxis.x;
  5690. result.m[1] = xaxis.y;
  5691. result.m[2] = xaxis.z;
  5692. result.m[3] = 0.0;
  5693. result.m[4] = yaxis.x;
  5694. result.m[5] = yaxis.y;
  5695. result.m[6] = yaxis.z;
  5696. result.m[7] = 0.0;
  5697. result.m[8] = zaxis.x;
  5698. result.m[9] = zaxis.y;
  5699. result.m[10] = zaxis.z;
  5700. result.m[11] = 0.0;
  5701. result.m[12] = 0.0;
  5702. result.m[13] = 0.0;
  5703. result.m[14] = 0.0;
  5704. result.m[15] = 1.0;
  5705. result._markAsUpdated();
  5706. };
  5707. /**
  5708. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5709. */
  5710. Matrix.FromQuaternionToRef = function (quat, result) {
  5711. var xx = quat.x * quat.x;
  5712. var yy = quat.y * quat.y;
  5713. var zz = quat.z * quat.z;
  5714. var xy = quat.x * quat.y;
  5715. var zw = quat.z * quat.w;
  5716. var zx = quat.z * quat.x;
  5717. var yw = quat.y * quat.w;
  5718. var yz = quat.y * quat.z;
  5719. var xw = quat.x * quat.w;
  5720. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5721. result.m[1] = 2.0 * (xy + zw);
  5722. result.m[2] = 2.0 * (zx - yw);
  5723. result.m[3] = 0.0;
  5724. result.m[4] = 2.0 * (xy - zw);
  5725. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5726. result.m[6] = 2.0 * (yz + xw);
  5727. result.m[7] = 0.0;
  5728. result.m[8] = 2.0 * (zx + yw);
  5729. result.m[9] = 2.0 * (yz - xw);
  5730. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5731. result.m[11] = 0.0;
  5732. result.m[12] = 0.0;
  5733. result.m[13] = 0.0;
  5734. result.m[14] = 0.0;
  5735. result.m[15] = 1.0;
  5736. result._markAsUpdated();
  5737. };
  5738. Matrix._tempQuaternion = new Quaternion();
  5739. Matrix._xAxis = Vector3.Zero();
  5740. Matrix._yAxis = Vector3.Zero();
  5741. Matrix._zAxis = Vector3.Zero();
  5742. Matrix._updateFlagSeed = 0;
  5743. Matrix._identityReadOnly = Matrix.Identity();
  5744. return Matrix;
  5745. }());
  5746. BABYLON.Matrix = Matrix;
  5747. var Plane = /** @class */ (function () {
  5748. /**
  5749. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5750. */
  5751. function Plane(a, b, c, d) {
  5752. this.normal = new Vector3(a, b, c);
  5753. this.d = d;
  5754. }
  5755. /**
  5756. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5757. */
  5758. Plane.prototype.asArray = function () {
  5759. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5760. };
  5761. // Methods
  5762. /**
  5763. * Returns a new plane copied from the current Plane.
  5764. */
  5765. Plane.prototype.clone = function () {
  5766. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5767. };
  5768. /**
  5769. * Returns the string "Plane".
  5770. */
  5771. Plane.prototype.getClassName = function () {
  5772. return "Plane";
  5773. };
  5774. /**
  5775. * Returns the Plane hash code.
  5776. */
  5777. Plane.prototype.getHashCode = function () {
  5778. var hash = this.normal.getHashCode();
  5779. hash = (hash * 397) ^ (this.d || 0);
  5780. return hash;
  5781. };
  5782. /**
  5783. * Normalize the current Plane in place.
  5784. * Returns the updated Plane.
  5785. */
  5786. Plane.prototype.normalize = function () {
  5787. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5788. var magnitude = 0.0;
  5789. if (norm !== 0) {
  5790. magnitude = 1.0 / norm;
  5791. }
  5792. this.normal.x *= magnitude;
  5793. this.normal.y *= magnitude;
  5794. this.normal.z *= magnitude;
  5795. this.d *= magnitude;
  5796. return this;
  5797. };
  5798. /**
  5799. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5800. */
  5801. Plane.prototype.transform = function (transformation) {
  5802. var transposedMatrix = Matrix.Transpose(transformation);
  5803. var x = this.normal.x;
  5804. var y = this.normal.y;
  5805. var z = this.normal.z;
  5806. var d = this.d;
  5807. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5808. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5809. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5810. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5811. return new Plane(normalX, normalY, normalZ, finalD);
  5812. };
  5813. /**
  5814. * Returns the dot product (float) of the point coordinates and the plane normal.
  5815. */
  5816. Plane.prototype.dotCoordinate = function (point) {
  5817. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5818. };
  5819. /**
  5820. * Updates the current Plane from the plane defined by the three passed points.
  5821. * Returns the updated Plane.
  5822. */
  5823. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5824. var x1 = point2.x - point1.x;
  5825. var y1 = point2.y - point1.y;
  5826. var z1 = point2.z - point1.z;
  5827. var x2 = point3.x - point1.x;
  5828. var y2 = point3.y - point1.y;
  5829. var z2 = point3.z - point1.z;
  5830. var yz = (y1 * z2) - (z1 * y2);
  5831. var xz = (z1 * x2) - (x1 * z2);
  5832. var xy = (x1 * y2) - (y1 * x2);
  5833. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5834. var invPyth;
  5835. if (pyth !== 0) {
  5836. invPyth = 1.0 / pyth;
  5837. }
  5838. else {
  5839. invPyth = 0.0;
  5840. }
  5841. this.normal.x = yz * invPyth;
  5842. this.normal.y = xz * invPyth;
  5843. this.normal.z = xy * invPyth;
  5844. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5845. return this;
  5846. };
  5847. /**
  5848. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5849. */
  5850. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5851. var dot = Vector3.Dot(this.normal, direction);
  5852. return (dot <= epsilon);
  5853. };
  5854. /**
  5855. * Returns the signed distance (float) from the passed point to the Plane.
  5856. */
  5857. Plane.prototype.signedDistanceTo = function (point) {
  5858. return Vector3.Dot(point, this.normal) + this.d;
  5859. };
  5860. // Statics
  5861. /**
  5862. * Returns a new Plane from the passed array.
  5863. */
  5864. Plane.FromArray = function (array) {
  5865. return new Plane(array[0], array[1], array[2], array[3]);
  5866. };
  5867. /**
  5868. * Returns a new Plane defined by the three passed points.
  5869. */
  5870. Plane.FromPoints = function (point1, point2, point3) {
  5871. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5872. result.copyFromPoints(point1, point2, point3);
  5873. return result;
  5874. };
  5875. /**
  5876. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5877. * Note : the vector "normal" is updated because normalized.
  5878. */
  5879. Plane.FromPositionAndNormal = function (origin, normal) {
  5880. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5881. normal.normalize();
  5882. result.normal = normal;
  5883. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5884. return result;
  5885. };
  5886. /**
  5887. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5888. */
  5889. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5890. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5891. return Vector3.Dot(point, normal) + d;
  5892. };
  5893. return Plane;
  5894. }());
  5895. BABYLON.Plane = Plane;
  5896. var Viewport = /** @class */ (function () {
  5897. /**
  5898. * Creates a Viewport object located at (x, y) and sized (width, height).
  5899. */
  5900. function Viewport(x, y, width, height) {
  5901. this.x = x;
  5902. this.y = y;
  5903. this.width = width;
  5904. this.height = height;
  5905. }
  5906. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5907. if (renderWidthOrEngine.getRenderWidth) {
  5908. var engine = renderWidthOrEngine;
  5909. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5910. }
  5911. var renderWidth = renderWidthOrEngine;
  5912. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5913. };
  5914. /**
  5915. * Returns a new Viewport copied from the current one.
  5916. */
  5917. Viewport.prototype.clone = function () {
  5918. return new Viewport(this.x, this.y, this.width, this.height);
  5919. };
  5920. return Viewport;
  5921. }());
  5922. BABYLON.Viewport = Viewport;
  5923. var Frustum = /** @class */ (function () {
  5924. function Frustum() {
  5925. }
  5926. /**
  5927. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5928. */
  5929. Frustum.GetPlanes = function (transform) {
  5930. var frustumPlanes = [];
  5931. for (var index = 0; index < 6; index++) {
  5932. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5933. }
  5934. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5935. return frustumPlanes;
  5936. };
  5937. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5938. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5939. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5940. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5941. frustumPlane.d = transform.m[15] + transform.m[14];
  5942. frustumPlane.normalize();
  5943. };
  5944. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5945. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5946. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5947. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5948. frustumPlane.d = transform.m[15] - transform.m[14];
  5949. frustumPlane.normalize();
  5950. };
  5951. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5952. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5953. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5954. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5955. frustumPlane.d = transform.m[15] + transform.m[12];
  5956. frustumPlane.normalize();
  5957. };
  5958. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5959. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5960. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5961. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5962. frustumPlane.d = transform.m[15] - transform.m[12];
  5963. frustumPlane.normalize();
  5964. };
  5965. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5966. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5967. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5968. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5969. frustumPlane.d = transform.m[15] - transform.m[13];
  5970. frustumPlane.normalize();
  5971. };
  5972. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5973. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5974. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5975. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5976. frustumPlane.d = transform.m[15] + transform.m[13];
  5977. frustumPlane.normalize();
  5978. };
  5979. /**
  5980. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5981. */
  5982. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5983. // Near
  5984. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5985. // Far
  5986. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5987. // Left
  5988. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5989. // Right
  5990. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5991. // Top
  5992. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5993. // Bottom
  5994. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5995. };
  5996. return Frustum;
  5997. }());
  5998. BABYLON.Frustum = Frustum;
  5999. var Space;
  6000. (function (Space) {
  6001. Space[Space["LOCAL"] = 0] = "LOCAL";
  6002. Space[Space["WORLD"] = 1] = "WORLD";
  6003. Space[Space["BONE"] = 2] = "BONE";
  6004. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6005. var Axis = /** @class */ (function () {
  6006. function Axis() {
  6007. }
  6008. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6009. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6010. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6011. return Axis;
  6012. }());
  6013. BABYLON.Axis = Axis;
  6014. ;
  6015. var BezierCurve = /** @class */ (function () {
  6016. function BezierCurve() {
  6017. }
  6018. /**
  6019. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6020. */
  6021. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6022. // Extract X (which is equal to time here)
  6023. var f0 = 1 - 3 * x2 + 3 * x1;
  6024. var f1 = 3 * x2 - 6 * x1;
  6025. var f2 = 3 * x1;
  6026. var refinedT = t;
  6027. for (var i = 0; i < 5; i++) {
  6028. var refinedT2 = refinedT * refinedT;
  6029. var refinedT3 = refinedT2 * refinedT;
  6030. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6031. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6032. refinedT -= (x - t) * slope;
  6033. refinedT = Math.min(1, Math.max(0, refinedT));
  6034. }
  6035. // Resolve cubic bezier for the given x
  6036. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6037. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6038. Math.pow(refinedT, 3);
  6039. };
  6040. return BezierCurve;
  6041. }());
  6042. BABYLON.BezierCurve = BezierCurve;
  6043. var Orientation;
  6044. (function (Orientation) {
  6045. Orientation[Orientation["CW"] = 0] = "CW";
  6046. Orientation[Orientation["CCW"] = 1] = "CCW";
  6047. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6048. var Angle = /** @class */ (function () {
  6049. /**
  6050. * Creates an Angle object of "radians" radians (float).
  6051. */
  6052. function Angle(radians) {
  6053. var _this = this;
  6054. /**
  6055. * Returns the Angle value in degrees (float).
  6056. */
  6057. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6058. /**
  6059. * Returns the Angle value in radians (float).
  6060. */
  6061. this.radians = function () { return _this._radians; };
  6062. this._radians = radians;
  6063. if (this._radians < 0.0)
  6064. this._radians += (2.0 * Math.PI);
  6065. }
  6066. /**
  6067. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6068. */
  6069. Angle.BetweenTwoPoints = function (a, b) {
  6070. var delta = b.subtract(a);
  6071. var theta = Math.atan2(delta.y, delta.x);
  6072. return new Angle(theta);
  6073. };
  6074. /**
  6075. * Returns a new Angle object from the passed float in radians.
  6076. */
  6077. Angle.FromRadians = function (radians) {
  6078. return new Angle(radians);
  6079. };
  6080. /**
  6081. * Returns a new Angle object from the passed float in degrees.
  6082. */
  6083. Angle.FromDegrees = function (degrees) {
  6084. return new Angle(degrees * Math.PI / 180.0);
  6085. };
  6086. return Angle;
  6087. }());
  6088. BABYLON.Angle = Angle;
  6089. var Arc2 = /** @class */ (function () {
  6090. /**
  6091. * Creates an Arc object from the three passed points : start, middle and end.
  6092. */
  6093. function Arc2(startPoint, midPoint, endPoint) {
  6094. this.startPoint = startPoint;
  6095. this.midPoint = midPoint;
  6096. this.endPoint = endPoint;
  6097. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6098. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6099. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6100. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6101. 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);
  6102. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6103. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6104. var a1 = this.startAngle.degrees();
  6105. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6106. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6107. // angles correction
  6108. if (a2 - a1 > +180.0)
  6109. a2 -= 360.0;
  6110. if (a2 - a1 < -180.0)
  6111. a2 += 360.0;
  6112. if (a3 - a2 > +180.0)
  6113. a3 -= 360.0;
  6114. if (a3 - a2 < -180.0)
  6115. a3 += 360.0;
  6116. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6117. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6118. }
  6119. return Arc2;
  6120. }());
  6121. BABYLON.Arc2 = Arc2;
  6122. var Path2 = /** @class */ (function () {
  6123. /**
  6124. * Creates a Path2 object from the starting 2D coordinates x and y.
  6125. */
  6126. function Path2(x, y) {
  6127. this._points = new Array();
  6128. this._length = 0.0;
  6129. this.closed = false;
  6130. this._points.push(new Vector2(x, y));
  6131. }
  6132. /**
  6133. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6134. * Returns the updated Path2.
  6135. */
  6136. Path2.prototype.addLineTo = function (x, y) {
  6137. if (this.closed) {
  6138. //Tools.Error("cannot add lines to closed paths");
  6139. return this;
  6140. }
  6141. var newPoint = new Vector2(x, y);
  6142. var previousPoint = this._points[this._points.length - 1];
  6143. this._points.push(newPoint);
  6144. this._length += newPoint.subtract(previousPoint).length();
  6145. return this;
  6146. };
  6147. /**
  6148. * 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.
  6149. * Returns the updated Path2.
  6150. */
  6151. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6152. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6153. if (this.closed) {
  6154. //Tools.Error("cannot add arcs to closed paths");
  6155. return this;
  6156. }
  6157. var startPoint = this._points[this._points.length - 1];
  6158. var midPoint = new Vector2(midX, midY);
  6159. var endPoint = new Vector2(endX, endY);
  6160. var arc = new Arc2(startPoint, midPoint, endPoint);
  6161. var increment = arc.angle.radians() / numberOfSegments;
  6162. if (arc.orientation === Orientation.CW)
  6163. increment *= -1;
  6164. var currentAngle = arc.startAngle.radians() + increment;
  6165. for (var i = 0; i < numberOfSegments; i++) {
  6166. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6167. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6168. this.addLineTo(x, y);
  6169. currentAngle += increment;
  6170. }
  6171. return this;
  6172. };
  6173. /**
  6174. * Closes the Path2.
  6175. * Returns the Path2.
  6176. */
  6177. Path2.prototype.close = function () {
  6178. this.closed = true;
  6179. return this;
  6180. };
  6181. /**
  6182. * Returns the Path2 total length (float).
  6183. */
  6184. Path2.prototype.length = function () {
  6185. var result = this._length;
  6186. if (!this.closed) {
  6187. var lastPoint = this._points[this._points.length - 1];
  6188. var firstPoint = this._points[0];
  6189. result += (firstPoint.subtract(lastPoint).length());
  6190. }
  6191. return result;
  6192. };
  6193. /**
  6194. * Returns the Path2 internal array of points.
  6195. */
  6196. Path2.prototype.getPoints = function () {
  6197. return this._points;
  6198. };
  6199. /**
  6200. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6201. */
  6202. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6203. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6204. //Tools.Error("normalized length position should be between 0 and 1.");
  6205. return Vector2.Zero();
  6206. }
  6207. var lengthPosition = normalizedLengthPosition * this.length();
  6208. var previousOffset = 0;
  6209. for (var i = 0; i < this._points.length; i++) {
  6210. var j = (i + 1) % this._points.length;
  6211. var a = this._points[i];
  6212. var b = this._points[j];
  6213. var bToA = b.subtract(a);
  6214. var nextOffset = (bToA.length() + previousOffset);
  6215. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6216. var dir = bToA.normalize();
  6217. var localOffset = lengthPosition - previousOffset;
  6218. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6219. }
  6220. previousOffset = nextOffset;
  6221. }
  6222. //Tools.Error("internal error");
  6223. return Vector2.Zero();
  6224. };
  6225. /**
  6226. * Returns a new Path2 starting at the coordinates (x, y).
  6227. */
  6228. Path2.StartingAt = function (x, y) {
  6229. return new Path2(x, y);
  6230. };
  6231. return Path2;
  6232. }());
  6233. BABYLON.Path2 = Path2;
  6234. var Path3D = /** @class */ (function () {
  6235. /**
  6236. * new Path3D(path, normal, raw)
  6237. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6238. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6239. * path : an array of Vector3, the curve axis of the Path3D
  6240. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6241. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6242. */
  6243. function Path3D(path, firstNormal, raw) {
  6244. if (firstNormal === void 0) { firstNormal = null; }
  6245. this.path = path;
  6246. this._curve = new Array();
  6247. this._distances = new Array();
  6248. this._tangents = new Array();
  6249. this._normals = new Array();
  6250. this._binormals = new Array();
  6251. for (var p = 0; p < path.length; p++) {
  6252. this._curve[p] = path[p].clone(); // hard copy
  6253. }
  6254. this._raw = raw || false;
  6255. this._compute(firstNormal);
  6256. }
  6257. /**
  6258. * Returns the Path3D array of successive Vector3 designing its curve.
  6259. */
  6260. Path3D.prototype.getCurve = function () {
  6261. return this._curve;
  6262. };
  6263. /**
  6264. * Returns an array populated with tangent vectors on each Path3D curve point.
  6265. */
  6266. Path3D.prototype.getTangents = function () {
  6267. return this._tangents;
  6268. };
  6269. /**
  6270. * Returns an array populated with normal vectors on each Path3D curve point.
  6271. */
  6272. Path3D.prototype.getNormals = function () {
  6273. return this._normals;
  6274. };
  6275. /**
  6276. * Returns an array populated with binormal vectors on each Path3D curve point.
  6277. */
  6278. Path3D.prototype.getBinormals = function () {
  6279. return this._binormals;
  6280. };
  6281. /**
  6282. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6283. */
  6284. Path3D.prototype.getDistances = function () {
  6285. return this._distances;
  6286. };
  6287. /**
  6288. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6289. * Returns the same object updated.
  6290. */
  6291. Path3D.prototype.update = function (path, firstNormal) {
  6292. if (firstNormal === void 0) { firstNormal = null; }
  6293. for (var p = 0; p < path.length; p++) {
  6294. this._curve[p].x = path[p].x;
  6295. this._curve[p].y = path[p].y;
  6296. this._curve[p].z = path[p].z;
  6297. }
  6298. this._compute(firstNormal);
  6299. return this;
  6300. };
  6301. // private function compute() : computes tangents, normals and binormals
  6302. Path3D.prototype._compute = function (firstNormal) {
  6303. var l = this._curve.length;
  6304. // first and last tangents
  6305. this._tangents[0] = this._getFirstNonNullVector(0);
  6306. if (!this._raw) {
  6307. this._tangents[0].normalize();
  6308. }
  6309. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6310. if (!this._raw) {
  6311. this._tangents[l - 1].normalize();
  6312. }
  6313. // normals and binormals at first point : arbitrary vector with _normalVector()
  6314. var tg0 = this._tangents[0];
  6315. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6316. this._normals[0] = pp0;
  6317. if (!this._raw) {
  6318. this._normals[0].normalize();
  6319. }
  6320. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6321. if (!this._raw) {
  6322. this._binormals[0].normalize();
  6323. }
  6324. this._distances[0] = 0.0;
  6325. // normals and binormals : next points
  6326. var prev; // previous vector (segment)
  6327. var cur; // current vector (segment)
  6328. var curTang; // current tangent
  6329. // previous normal
  6330. var prevBinor; // previous binormal
  6331. for (var i = 1; i < l; i++) {
  6332. // tangents
  6333. prev = this._getLastNonNullVector(i);
  6334. if (i < l - 1) {
  6335. cur = this._getFirstNonNullVector(i);
  6336. this._tangents[i] = prev.add(cur);
  6337. this._tangents[i].normalize();
  6338. }
  6339. this._distances[i] = this._distances[i - 1] + prev.length();
  6340. // normals and binormals
  6341. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6342. curTang = this._tangents[i];
  6343. prevBinor = this._binormals[i - 1];
  6344. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6345. if (!this._raw) {
  6346. this._normals[i].normalize();
  6347. }
  6348. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6349. if (!this._raw) {
  6350. this._binormals[i].normalize();
  6351. }
  6352. }
  6353. };
  6354. // private function getFirstNonNullVector(index)
  6355. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6356. Path3D.prototype._getFirstNonNullVector = function (index) {
  6357. var i = 1;
  6358. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6359. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6360. i++;
  6361. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6362. }
  6363. return nNVector;
  6364. };
  6365. // private function getLastNonNullVector(index)
  6366. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6367. Path3D.prototype._getLastNonNullVector = function (index) {
  6368. var i = 1;
  6369. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6370. while (nLVector.length() === 0 && index > i + 1) {
  6371. i++;
  6372. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6373. }
  6374. return nLVector;
  6375. };
  6376. // private function normalVector(v0, vt, va) :
  6377. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6378. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6379. Path3D.prototype._normalVector = function (v0, vt, va) {
  6380. var normal0;
  6381. var tgl = vt.length();
  6382. if (tgl === 0.0) {
  6383. tgl = 1.0;
  6384. }
  6385. if (va === undefined || va === null) {
  6386. var point;
  6387. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6388. point = new Vector3(0.0, -1.0, 0.0);
  6389. }
  6390. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6391. point = new Vector3(1.0, 0.0, 0.0);
  6392. }
  6393. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6394. point = new Vector3(0.0, 0.0, 1.0);
  6395. }
  6396. else {
  6397. point = Vector3.Zero();
  6398. }
  6399. normal0 = Vector3.Cross(vt, point);
  6400. }
  6401. else {
  6402. normal0 = Vector3.Cross(vt, va);
  6403. Vector3.CrossToRef(normal0, vt, normal0);
  6404. }
  6405. normal0.normalize();
  6406. return normal0;
  6407. };
  6408. return Path3D;
  6409. }());
  6410. BABYLON.Path3D = Path3D;
  6411. var Curve3 = /** @class */ (function () {
  6412. /**
  6413. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6414. * A Curve3 is designed from a series of successive Vector3.
  6415. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6416. */
  6417. function Curve3(points) {
  6418. this._length = 0.0;
  6419. this._points = points;
  6420. this._length = this._computeLength(points);
  6421. }
  6422. /**
  6423. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6424. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6425. * @param v1 (Vector3) the control point
  6426. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6427. * @param nbPoints (integer) the wanted number of points in the curve
  6428. */
  6429. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6430. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6431. var bez = new Array();
  6432. var equation = function (t, val0, val1, val2) {
  6433. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6434. return res;
  6435. };
  6436. for (var i = 0; i <= nbPoints; i++) {
  6437. 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)));
  6438. }
  6439. return new Curve3(bez);
  6440. };
  6441. /**
  6442. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6443. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6444. * @param v1 (Vector3) the first control point
  6445. * @param v2 (Vector3) the second control point
  6446. * @param v3 (Vector3) the end point of the Cubic Bezier
  6447. * @param nbPoints (integer) the wanted number of points in the curve
  6448. */
  6449. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6450. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6451. var bez = new Array();
  6452. var equation = function (t, val0, val1, val2, val3) {
  6453. 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;
  6454. return res;
  6455. };
  6456. for (var i = 0; i <= nbPoints; i++) {
  6457. 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)));
  6458. }
  6459. return new Curve3(bez);
  6460. };
  6461. /**
  6462. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6463. * @param p1 (Vector3) the origin point of the Hermite Spline
  6464. * @param t1 (Vector3) the tangent vector at the origin point
  6465. * @param p2 (Vector3) the end point of the Hermite Spline
  6466. * @param t2 (Vector3) the tangent vector at the end point
  6467. * @param nbPoints (integer) the wanted number of points in the curve
  6468. */
  6469. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6470. var hermite = new Array();
  6471. var step = 1.0 / nbPoints;
  6472. for (var i = 0; i <= nbPoints; i++) {
  6473. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6474. }
  6475. return new Curve3(hermite);
  6476. };
  6477. /**
  6478. * Returns a Curve3 object along a CatmullRom Spline curve :
  6479. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6480. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6481. */
  6482. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6483. var totalPoints = new Array();
  6484. totalPoints.push(points[0].clone());
  6485. Array.prototype.push.apply(totalPoints, points);
  6486. totalPoints.push(points[points.length - 1].clone());
  6487. var catmullRom = new Array();
  6488. var step = 1.0 / nbPoints;
  6489. var amount = 0.0;
  6490. for (var i = 0; i < totalPoints.length - 3; i++) {
  6491. amount = 0;
  6492. for (var c = 0; c < nbPoints; c++) {
  6493. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6494. amount += step;
  6495. }
  6496. }
  6497. i--;
  6498. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6499. return new Curve3(catmullRom);
  6500. };
  6501. /**
  6502. * Returns the Curve3 stored array of successive Vector3
  6503. */
  6504. Curve3.prototype.getPoints = function () {
  6505. return this._points;
  6506. };
  6507. /**
  6508. * Returns the computed length (float) of the curve.
  6509. */
  6510. Curve3.prototype.length = function () {
  6511. return this._length;
  6512. };
  6513. /**
  6514. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6515. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6516. * curveA and curveB keep unchanged.
  6517. */
  6518. Curve3.prototype.continue = function (curve) {
  6519. var lastPoint = this._points[this._points.length - 1];
  6520. var continuedPoints = this._points.slice();
  6521. var curvePoints = curve.getPoints();
  6522. for (var i = 1; i < curvePoints.length; i++) {
  6523. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6524. }
  6525. var continuedCurve = new Curve3(continuedPoints);
  6526. return continuedCurve;
  6527. };
  6528. Curve3.prototype._computeLength = function (path) {
  6529. var l = 0;
  6530. for (var i = 1; i < path.length; i++) {
  6531. l += (path[i].subtract(path[i - 1])).length();
  6532. }
  6533. return l;
  6534. };
  6535. return Curve3;
  6536. }());
  6537. BABYLON.Curve3 = Curve3;
  6538. // Vertex formats
  6539. var PositionNormalVertex = /** @class */ (function () {
  6540. function PositionNormalVertex(position, normal) {
  6541. if (position === void 0) { position = Vector3.Zero(); }
  6542. if (normal === void 0) { normal = Vector3.Up(); }
  6543. this.position = position;
  6544. this.normal = normal;
  6545. }
  6546. PositionNormalVertex.prototype.clone = function () {
  6547. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6548. };
  6549. return PositionNormalVertex;
  6550. }());
  6551. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6552. var PositionNormalTextureVertex = /** @class */ (function () {
  6553. function PositionNormalTextureVertex(position, normal, uv) {
  6554. if (position === void 0) { position = Vector3.Zero(); }
  6555. if (normal === void 0) { normal = Vector3.Up(); }
  6556. if (uv === void 0) { uv = Vector2.Zero(); }
  6557. this.position = position;
  6558. this.normal = normal;
  6559. this.uv = uv;
  6560. }
  6561. PositionNormalTextureVertex.prototype.clone = function () {
  6562. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6563. };
  6564. return PositionNormalTextureVertex;
  6565. }());
  6566. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6567. // Temporary pre-allocated objects for engine internal use
  6568. // usage in any internal function :
  6569. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6570. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6571. var Tmp = /** @class */ (function () {
  6572. function Tmp() {
  6573. }
  6574. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6575. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6576. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6577. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6578. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6579. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6580. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6581. Matrix.Zero(), Matrix.Zero(),
  6582. Matrix.Zero(), Matrix.Zero(),
  6583. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6584. return Tmp;
  6585. }());
  6586. BABYLON.Tmp = Tmp;
  6587. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6588. var MathTmp = /** @class */ (function () {
  6589. function MathTmp() {
  6590. }
  6591. MathTmp.Vector3 = [Vector3.Zero()];
  6592. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6593. MathTmp.Quaternion = [Quaternion.Zero()];
  6594. return MathTmp;
  6595. }());
  6596. })(BABYLON || (BABYLON = {}));
  6597. //# sourceMappingURL=babylon.math.js.map
  6598. var BABYLON;
  6599. (function (BABYLON) {
  6600. var Scalar = /** @class */ (function () {
  6601. function Scalar() {
  6602. }
  6603. /**
  6604. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6605. */
  6606. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6607. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6608. var num = a - b;
  6609. return -epsilon <= num && num <= epsilon;
  6610. };
  6611. /**
  6612. * Returns a string : the upper case translation of the number i to hexadecimal.
  6613. */
  6614. Scalar.ToHex = function (i) {
  6615. var str = i.toString(16);
  6616. if (i <= 15) {
  6617. return ("0" + str).toUpperCase();
  6618. }
  6619. return str.toUpperCase();
  6620. };
  6621. /**
  6622. * Returns -1 if value is negative and +1 is value is positive.
  6623. * Returns the value itself if it's equal to zero.
  6624. */
  6625. Scalar.Sign = function (value) {
  6626. value = +value; // convert to a number
  6627. if (value === 0 || isNaN(value))
  6628. return value;
  6629. return value > 0 ? 1 : -1;
  6630. };
  6631. /**
  6632. * Returns the value itself if it's between min and max.
  6633. * Returns min if the value is lower than min.
  6634. * Returns max if the value is greater than max.
  6635. */
  6636. Scalar.Clamp = function (value, min, max) {
  6637. if (min === void 0) { min = 0; }
  6638. if (max === void 0) { max = 1; }
  6639. return Math.min(max, Math.max(min, value));
  6640. };
  6641. /**
  6642. * Returns the log2 of value.
  6643. */
  6644. Scalar.Log2 = function (value) {
  6645. return Math.log(value) * Math.LOG2E;
  6646. };
  6647. /**
  6648. * Loops the value, so that it is never larger than length and never smaller than 0.
  6649. *
  6650. * This is similar to the modulo operator but it works with floating point numbers.
  6651. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6652. * With t = 5 and length = 2.5, the result would be 0.0.
  6653. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6654. */
  6655. Scalar.Repeat = function (value, length) {
  6656. return value - Math.floor(value / length) * length;
  6657. };
  6658. /**
  6659. * Normalize the value between 0.0 and 1.0 using min and max values
  6660. */
  6661. Scalar.Normalize = function (value, min, max) {
  6662. return (value - min) / (max - min);
  6663. };
  6664. /**
  6665. * Denormalize the value from 0.0 and 1.0 using min and max values
  6666. */
  6667. Scalar.Denormalize = function (normalized, min, max) {
  6668. return (normalized * (max - min) + min);
  6669. };
  6670. /**
  6671. * Calculates the shortest difference between two given angles given in degrees.
  6672. */
  6673. Scalar.DeltaAngle = function (current, target) {
  6674. var num = Scalar.Repeat(target - current, 360.0);
  6675. if (num > 180.0) {
  6676. num -= 360.0;
  6677. }
  6678. return num;
  6679. };
  6680. /**
  6681. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6682. *
  6683. * The returned value will move back and forth between 0 and length
  6684. */
  6685. Scalar.PingPong = function (tx, length) {
  6686. var t = Scalar.Repeat(tx, length * 2.0);
  6687. return length - Math.abs(t - length);
  6688. };
  6689. /**
  6690. * Interpolates between min and max with smoothing at the limits.
  6691. *
  6692. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6693. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6694. */
  6695. Scalar.SmoothStep = function (from, to, tx) {
  6696. var t = Scalar.Clamp(tx);
  6697. t = -2.0 * t * t * t + 3.0 * t * t;
  6698. return to * t + from * (1.0 - t);
  6699. };
  6700. /**
  6701. * Moves a value current towards target.
  6702. *
  6703. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6704. * Negative values of maxDelta pushes the value away from target.
  6705. */
  6706. Scalar.MoveTowards = function (current, target, maxDelta) {
  6707. var result = 0;
  6708. if (Math.abs(target - current) <= maxDelta) {
  6709. result = target;
  6710. }
  6711. else {
  6712. result = current + Scalar.Sign(target - current) * maxDelta;
  6713. }
  6714. return result;
  6715. };
  6716. /**
  6717. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6718. *
  6719. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6720. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6721. */
  6722. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6723. var num = Scalar.DeltaAngle(current, target);
  6724. var result = 0;
  6725. if (-maxDelta < num && num < maxDelta) {
  6726. result = target;
  6727. }
  6728. else {
  6729. target = current + num;
  6730. result = Scalar.MoveTowards(current, target, maxDelta);
  6731. }
  6732. return result;
  6733. };
  6734. /**
  6735. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6736. */
  6737. Scalar.Lerp = function (start, end, amount) {
  6738. return start + ((end - start) * amount);
  6739. };
  6740. /**
  6741. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6742. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6743. */
  6744. Scalar.LerpAngle = function (start, end, amount) {
  6745. var num = Scalar.Repeat(end - start, 360.0);
  6746. if (num > 180.0) {
  6747. num -= 360.0;
  6748. }
  6749. return start + num * Scalar.Clamp(amount);
  6750. };
  6751. /**
  6752. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6753. */
  6754. Scalar.InverseLerp = function (a, b, value) {
  6755. var result = 0;
  6756. if (a != b) {
  6757. result = Scalar.Clamp((value - a) / (b - a));
  6758. }
  6759. else {
  6760. result = 0.0;
  6761. }
  6762. return result;
  6763. };
  6764. /**
  6765. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6766. */
  6767. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6768. var squared = amount * amount;
  6769. var cubed = amount * squared;
  6770. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6771. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6772. var part3 = (cubed - (2.0 * squared)) + amount;
  6773. var part4 = cubed - squared;
  6774. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6775. };
  6776. /**
  6777. * Returns a random float number between and min and max values
  6778. */
  6779. Scalar.RandomRange = function (min, max) {
  6780. if (min === max)
  6781. return min;
  6782. return ((Math.random() * (max - min)) + min);
  6783. };
  6784. /**
  6785. * This function returns percentage of a number in a given range.
  6786. *
  6787. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6788. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6789. */
  6790. Scalar.RangeToPercent = function (number, min, max) {
  6791. return ((number - min) / (max - min));
  6792. };
  6793. /**
  6794. * This function returns number that corresponds to the percentage in a given range.
  6795. *
  6796. * PercentToRange(0.34,0,100) will return 34.
  6797. */
  6798. Scalar.PercentToRange = function (percent, min, max) {
  6799. return ((max - min) * percent + min);
  6800. };
  6801. /**
  6802. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6803. * @param angle The angle to normalize in radian.
  6804. * @return The converted angle.
  6805. */
  6806. Scalar.NormalizeRadians = function (angle) {
  6807. // More precise but slower version kept for reference.
  6808. // angle = angle % Tools.TwoPi;
  6809. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6810. //if (angle > Math.PI) {
  6811. // angle -= Tools.TwoPi;
  6812. //}
  6813. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6814. return angle;
  6815. };
  6816. /**
  6817. * Two pi constants convenient for computation.
  6818. */
  6819. Scalar.TwoPi = Math.PI * 2;
  6820. return Scalar;
  6821. }());
  6822. BABYLON.Scalar = Scalar;
  6823. })(BABYLON || (BABYLON = {}));
  6824. //# sourceMappingURL=babylon.math.scalar.js.map
  6825. //# sourceMappingURL=babylon.mixins.js.map
  6826. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6827. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6828. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6829. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6830. //# sourceMappingURL=babylon.webgl2.js.map
  6831. var BABYLON;
  6832. (function (BABYLON) {
  6833. var __decoratorInitialStore = {};
  6834. var __mergedStore = {};
  6835. var _copySource = function (creationFunction, source, instanciate) {
  6836. var destination = creationFunction();
  6837. // Tags
  6838. if (BABYLON.Tags) {
  6839. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6840. }
  6841. var classStore = getMergedStore(destination);
  6842. // Properties
  6843. for (var property in classStore) {
  6844. var propertyDescriptor = classStore[property];
  6845. var sourceProperty = source[property];
  6846. var propertyType = propertyDescriptor.type;
  6847. if (sourceProperty !== undefined && sourceProperty !== null) {
  6848. switch (propertyType) {
  6849. case 0: // Value
  6850. case 6:// Mesh reference
  6851. destination[property] = sourceProperty;
  6852. break;
  6853. case 1:// Texture
  6854. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6855. break;
  6856. case 2: // Color3
  6857. case 3: // FresnelParameters
  6858. case 4: // Vector2
  6859. case 5: // Vector3
  6860. case 7: // Color Curves
  6861. case 10:// Quaternion
  6862. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6863. break;
  6864. }
  6865. }
  6866. }
  6867. return destination;
  6868. };
  6869. function getDirectStore(target) {
  6870. var classKey = target.getClassName();
  6871. if (!__decoratorInitialStore[classKey]) {
  6872. __decoratorInitialStore[classKey] = {};
  6873. }
  6874. return __decoratorInitialStore[classKey];
  6875. }
  6876. /**
  6877. * Return the list of properties flagged as serializable
  6878. * @param target: host object
  6879. */
  6880. function getMergedStore(target) {
  6881. var classKey = target.getClassName();
  6882. if (__mergedStore[classKey]) {
  6883. return __mergedStore[classKey];
  6884. }
  6885. __mergedStore[classKey] = {};
  6886. var store = __mergedStore[classKey];
  6887. var currentTarget = target;
  6888. var currentKey = classKey;
  6889. while (currentKey) {
  6890. var initialStore = __decoratorInitialStore[currentKey];
  6891. for (var property in initialStore) {
  6892. store[property] = initialStore[property];
  6893. }
  6894. var parent_1 = void 0;
  6895. var done = false;
  6896. do {
  6897. parent_1 = Object.getPrototypeOf(currentTarget);
  6898. if (!parent_1.getClassName) {
  6899. done = true;
  6900. break;
  6901. }
  6902. if (parent_1.getClassName() !== currentKey) {
  6903. break;
  6904. }
  6905. currentTarget = parent_1;
  6906. } while (parent_1);
  6907. if (done) {
  6908. break;
  6909. }
  6910. currentKey = parent_1.getClassName();
  6911. currentTarget = parent_1;
  6912. }
  6913. return store;
  6914. }
  6915. function generateSerializableMember(type, sourceName) {
  6916. return function (target, propertyKey) {
  6917. var classStore = getDirectStore(target);
  6918. if (!classStore[propertyKey]) {
  6919. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6920. }
  6921. };
  6922. }
  6923. function generateExpandMember(setCallback, targetKey) {
  6924. if (targetKey === void 0) { targetKey = null; }
  6925. return function (target, propertyKey) {
  6926. var key = targetKey || ("_" + propertyKey);
  6927. Object.defineProperty(target, propertyKey, {
  6928. get: function () {
  6929. return this[key];
  6930. },
  6931. set: function (value) {
  6932. if (this[key] === value) {
  6933. return;
  6934. }
  6935. this[key] = value;
  6936. target[setCallback].apply(this);
  6937. },
  6938. enumerable: true,
  6939. configurable: true
  6940. });
  6941. };
  6942. }
  6943. function expandToProperty(callback, targetKey) {
  6944. if (targetKey === void 0) { targetKey = null; }
  6945. return generateExpandMember(callback, targetKey);
  6946. }
  6947. BABYLON.expandToProperty = expandToProperty;
  6948. function serialize(sourceName) {
  6949. return generateSerializableMember(0, sourceName); // value member
  6950. }
  6951. BABYLON.serialize = serialize;
  6952. function serializeAsTexture(sourceName) {
  6953. return generateSerializableMember(1, sourceName); // texture member
  6954. }
  6955. BABYLON.serializeAsTexture = serializeAsTexture;
  6956. function serializeAsColor3(sourceName) {
  6957. return generateSerializableMember(2, sourceName); // color3 member
  6958. }
  6959. BABYLON.serializeAsColor3 = serializeAsColor3;
  6960. function serializeAsFresnelParameters(sourceName) {
  6961. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6962. }
  6963. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6964. function serializeAsVector2(sourceName) {
  6965. return generateSerializableMember(4, sourceName); // vector2 member
  6966. }
  6967. BABYLON.serializeAsVector2 = serializeAsVector2;
  6968. function serializeAsVector3(sourceName) {
  6969. return generateSerializableMember(5, sourceName); // vector3 member
  6970. }
  6971. BABYLON.serializeAsVector3 = serializeAsVector3;
  6972. function serializeAsMeshReference(sourceName) {
  6973. return generateSerializableMember(6, sourceName); // mesh reference member
  6974. }
  6975. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6976. function serializeAsColorCurves(sourceName) {
  6977. return generateSerializableMember(7, sourceName); // color curves
  6978. }
  6979. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6980. function serializeAsColor4(sourceName) {
  6981. return generateSerializableMember(8, sourceName); // color 4
  6982. }
  6983. BABYLON.serializeAsColor4 = serializeAsColor4;
  6984. function serializeAsImageProcessingConfiguration(sourceName) {
  6985. return generateSerializableMember(9, sourceName); // image processing
  6986. }
  6987. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6988. function serializeAsQuaternion(sourceName) {
  6989. return generateSerializableMember(10, sourceName); // quaternion member
  6990. }
  6991. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6992. var SerializationHelper = /** @class */ (function () {
  6993. function SerializationHelper() {
  6994. }
  6995. SerializationHelper.Serialize = function (entity, serializationObject) {
  6996. if (!serializationObject) {
  6997. serializationObject = {};
  6998. }
  6999. // Tags
  7000. if (BABYLON.Tags) {
  7001. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7002. }
  7003. var serializedProperties = getMergedStore(entity);
  7004. // Properties
  7005. for (var property in serializedProperties) {
  7006. var propertyDescriptor = serializedProperties[property];
  7007. var targetPropertyName = propertyDescriptor.sourceName || property;
  7008. var propertyType = propertyDescriptor.type;
  7009. var sourceProperty = entity[property];
  7010. if (sourceProperty !== undefined && sourceProperty !== null) {
  7011. switch (propertyType) {
  7012. case 0:// Value
  7013. serializationObject[targetPropertyName] = sourceProperty;
  7014. break;
  7015. case 1:// Texture
  7016. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7017. break;
  7018. case 2:// Color3
  7019. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7020. break;
  7021. case 3:// FresnelParameters
  7022. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7023. break;
  7024. case 4:// Vector2
  7025. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7026. break;
  7027. case 5:// Vector3
  7028. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7029. break;
  7030. case 6:// Mesh reference
  7031. serializationObject[targetPropertyName] = sourceProperty.id;
  7032. break;
  7033. case 7:// Color Curves
  7034. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7035. break;
  7036. case 8:// Color 4
  7037. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7038. break;
  7039. case 9:// Image Processing
  7040. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7041. break;
  7042. }
  7043. }
  7044. }
  7045. return serializationObject;
  7046. };
  7047. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7048. if (rootUrl === void 0) { rootUrl = null; }
  7049. var destination = creationFunction();
  7050. if (!rootUrl) {
  7051. rootUrl = "";
  7052. }
  7053. // Tags
  7054. if (BABYLON.Tags) {
  7055. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7056. }
  7057. var classStore = getMergedStore(destination);
  7058. // Properties
  7059. for (var property in classStore) {
  7060. var propertyDescriptor = classStore[property];
  7061. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7062. var propertyType = propertyDescriptor.type;
  7063. if (sourceProperty !== undefined && sourceProperty !== null) {
  7064. var dest = destination;
  7065. switch (propertyType) {
  7066. case 0:// Value
  7067. dest[property] = sourceProperty;
  7068. break;
  7069. case 1:// Texture
  7070. if (scene) {
  7071. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7072. }
  7073. break;
  7074. case 2:// Color3
  7075. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7076. break;
  7077. case 3:// FresnelParameters
  7078. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7079. break;
  7080. case 4:// Vector2
  7081. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7082. break;
  7083. case 5:// Vector3
  7084. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7085. break;
  7086. case 6:// Mesh reference
  7087. if (scene) {
  7088. dest[property] = scene.getLastMeshByID(sourceProperty);
  7089. }
  7090. break;
  7091. case 7:// Color Curves
  7092. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7093. break;
  7094. case 8:// Color 4
  7095. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7096. break;
  7097. case 9:// Image Processing
  7098. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7099. break;
  7100. }
  7101. }
  7102. }
  7103. return destination;
  7104. };
  7105. SerializationHelper.Clone = function (creationFunction, source) {
  7106. return _copySource(creationFunction, source, false);
  7107. };
  7108. SerializationHelper.Instanciate = function (creationFunction, source) {
  7109. return _copySource(creationFunction, source, true);
  7110. };
  7111. return SerializationHelper;
  7112. }());
  7113. BABYLON.SerializationHelper = SerializationHelper;
  7114. })(BABYLON || (BABYLON = {}));
  7115. //# sourceMappingURL=babylon.decorators.js.map
  7116. var BABYLON;
  7117. (function (BABYLON) {
  7118. /**
  7119. * Wrapper class for promise with external resolve and reject.
  7120. */
  7121. var Deferred = /** @class */ (function () {
  7122. /**
  7123. * Constructor for this deferred object.
  7124. */
  7125. function Deferred() {
  7126. var _this = this;
  7127. this.promise = new Promise(function (resolve, reject) {
  7128. _this._resolve = resolve;
  7129. _this._reject = reject;
  7130. });
  7131. }
  7132. Object.defineProperty(Deferred.prototype, "resolve", {
  7133. /**
  7134. * The resolve method of the promise associated with this deferred object.
  7135. */
  7136. get: function () {
  7137. return this._resolve;
  7138. },
  7139. enumerable: true,
  7140. configurable: true
  7141. });
  7142. Object.defineProperty(Deferred.prototype, "reject", {
  7143. /**
  7144. * The reject method of the promise associated with this deferred object.
  7145. */
  7146. get: function () {
  7147. return this._reject;
  7148. },
  7149. enumerable: true,
  7150. configurable: true
  7151. });
  7152. return Deferred;
  7153. }());
  7154. BABYLON.Deferred = Deferred;
  7155. })(BABYLON || (BABYLON = {}));
  7156. //# sourceMappingURL=babylon.deferred.js.map
  7157. var BABYLON;
  7158. (function (BABYLON) {
  7159. /**
  7160. * A class serves as a medium between the observable and its observers
  7161. */
  7162. var EventState = /** @class */ (function () {
  7163. /**
  7164. * Create a new EventState
  7165. * @param mask defines the mask associated with this state
  7166. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7167. * @param target defines the original target of the state
  7168. * @param currentTarget defines the current target of the state
  7169. */
  7170. function EventState(mask, skipNextObservers, target, currentTarget) {
  7171. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7172. this.initalize(mask, skipNextObservers, target, currentTarget);
  7173. }
  7174. /**
  7175. * Initialize the current event state
  7176. * @param mask defines the mask associated with this state
  7177. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7178. * @param target defines the original target of the state
  7179. * @param currentTarget defines the current target of the state
  7180. * @returns the current event state
  7181. */
  7182. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7183. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7184. this.mask = mask;
  7185. this.skipNextObservers = skipNextObservers;
  7186. this.target = target;
  7187. this.currentTarget = currentTarget;
  7188. return this;
  7189. };
  7190. return EventState;
  7191. }());
  7192. BABYLON.EventState = EventState;
  7193. /**
  7194. * Represent an Observer registered to a given Observable object.
  7195. */
  7196. var Observer = /** @class */ (function () {
  7197. /**
  7198. * Creates a new observer
  7199. * @param callback defines the callback to call when the observer is notified
  7200. * @param mask defines the mask of the observer (used to filter notifications)
  7201. * @param scope defines the current scope used to restore the JS context
  7202. */
  7203. function Observer(
  7204. /**
  7205. * Defines the callback to call when the observer is notified
  7206. */
  7207. callback,
  7208. /**
  7209. * Defines the mask of the observer (used to filter notifications)
  7210. */
  7211. mask,
  7212. /**
  7213. * Defines the current scope used to restore the JS context
  7214. */
  7215. scope) {
  7216. if (scope === void 0) { scope = null; }
  7217. this.callback = callback;
  7218. this.mask = mask;
  7219. this.scope = scope;
  7220. /** @ignore */
  7221. this._willBeUnregistered = false;
  7222. /**
  7223. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7224. */
  7225. this.unregisterOnNextCall = false;
  7226. }
  7227. return Observer;
  7228. }());
  7229. BABYLON.Observer = Observer;
  7230. /**
  7231. * Represent a list of observers registered to multiple Observables object.
  7232. */
  7233. var MultiObserver = /** @class */ (function () {
  7234. function MultiObserver() {
  7235. }
  7236. /**
  7237. * Release associated resources
  7238. */
  7239. MultiObserver.prototype.dispose = function () {
  7240. if (this._observers && this._observables) {
  7241. for (var index = 0; index < this._observers.length; index++) {
  7242. this._observables[index].remove(this._observers[index]);
  7243. }
  7244. }
  7245. this._observers = null;
  7246. this._observables = null;
  7247. };
  7248. /**
  7249. * Raise a callback when one of the observable will notify
  7250. * @param observables defines a list of observables to watch
  7251. * @param callback defines the callback to call on notification
  7252. * @param mask defines the mask used to filter notifications
  7253. * @param scope defines the current scope used to restore the JS context
  7254. * @returns the new MultiObserver
  7255. */
  7256. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7257. if (mask === void 0) { mask = -1; }
  7258. if (scope === void 0) { scope = null; }
  7259. var result = new MultiObserver();
  7260. result._observers = new Array();
  7261. result._observables = observables;
  7262. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7263. var observable = observables_1[_i];
  7264. var observer = observable.add(callback, mask, false, scope);
  7265. if (observer) {
  7266. result._observers.push(observer);
  7267. }
  7268. }
  7269. return result;
  7270. };
  7271. return MultiObserver;
  7272. }());
  7273. BABYLON.MultiObserver = MultiObserver;
  7274. /**
  7275. * The Observable class is a simple implementation of the Observable pattern.
  7276. * 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.
  7277. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7278. * 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).
  7279. * 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.
  7280. */
  7281. var Observable = /** @class */ (function () {
  7282. /**
  7283. * Creates a new observable
  7284. * @param onObserverAdded defines a callback to call when a new observer is added
  7285. */
  7286. function Observable(onObserverAdded) {
  7287. this._observers = new Array();
  7288. this._eventState = new EventState(0);
  7289. if (onObserverAdded) {
  7290. this._onObserverAdded = onObserverAdded;
  7291. }
  7292. }
  7293. /**
  7294. * Create a new Observer with the specified callback
  7295. * @param callback the callback that will be executed for that Observer
  7296. * @param mask the mask used to filter observers
  7297. * @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.
  7298. * @param scope optional scope for the callback to be called from
  7299. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7300. * @returns the new observer created for the callback
  7301. */
  7302. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7303. if (mask === void 0) { mask = -1; }
  7304. if (insertFirst === void 0) { insertFirst = false; }
  7305. if (scope === void 0) { scope = null; }
  7306. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7307. if (!callback) {
  7308. return null;
  7309. }
  7310. var observer = new Observer(callback, mask, scope);
  7311. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7312. if (insertFirst) {
  7313. this._observers.unshift(observer);
  7314. }
  7315. else {
  7316. this._observers.push(observer);
  7317. }
  7318. if (this._onObserverAdded) {
  7319. this._onObserverAdded(observer);
  7320. }
  7321. return observer;
  7322. };
  7323. /**
  7324. * Remove an Observer from the Observable object
  7325. * @param observer the instance of the Observer to remove
  7326. * @returns false if it doesn't belong to this Observable
  7327. */
  7328. Observable.prototype.remove = function (observer) {
  7329. if (!observer) {
  7330. return false;
  7331. }
  7332. var index = this._observers.indexOf(observer);
  7333. if (index !== -1) {
  7334. this._observers.splice(index, 1);
  7335. return true;
  7336. }
  7337. return false;
  7338. };
  7339. /**
  7340. * Remove a callback from the Observable object
  7341. * @param callback the callback to remove
  7342. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7343. * @returns false if it doesn't belong to this Observable
  7344. */
  7345. Observable.prototype.removeCallback = function (callback, scope) {
  7346. for (var index = 0; index < this._observers.length; index++) {
  7347. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7348. this._observers.splice(index, 1);
  7349. return true;
  7350. }
  7351. }
  7352. return false;
  7353. };
  7354. Observable.prototype._deferUnregister = function (observer) {
  7355. var _this = this;
  7356. observer.unregisterOnNextCall = false;
  7357. observer._willBeUnregistered = true;
  7358. BABYLON.Tools.SetImmediate(function () {
  7359. _this.remove(observer);
  7360. });
  7361. };
  7362. /**
  7363. * Notify all Observers by calling their respective callback with the given data
  7364. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7365. * @param eventData defines the data to send to all observers
  7366. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7367. * @param target defines the original target of the state
  7368. * @param currentTarget defines the current target of the state
  7369. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7370. */
  7371. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7372. if (mask === void 0) { mask = -1; }
  7373. if (!this._observers.length) {
  7374. return true;
  7375. }
  7376. var state = this._eventState;
  7377. state.mask = mask;
  7378. state.target = target;
  7379. state.currentTarget = currentTarget;
  7380. state.skipNextObservers = false;
  7381. state.lastReturnValue = eventData;
  7382. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7383. var obs = _a[_i];
  7384. if (obs._willBeUnregistered) {
  7385. continue;
  7386. }
  7387. if (obs.mask & mask) {
  7388. if (obs.scope) {
  7389. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7390. }
  7391. else {
  7392. state.lastReturnValue = obs.callback(eventData, state);
  7393. }
  7394. if (obs.unregisterOnNextCall) {
  7395. this._deferUnregister(obs);
  7396. }
  7397. }
  7398. if (state.skipNextObservers) {
  7399. return false;
  7400. }
  7401. }
  7402. return true;
  7403. };
  7404. /**
  7405. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7406. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7407. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7408. * and it is crucial that all callbacks will be executed.
  7409. * The order of the callbacks is kept, callbacks are not executed parallel.
  7410. *
  7411. * @param eventData The data to be sent to each callback
  7412. * @param mask is used to filter observers defaults to -1
  7413. * @param target defines the callback target (see EventState)
  7414. * @param currentTarget defines he current object in the bubbling phase
  7415. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7416. */
  7417. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7418. var _this = this;
  7419. if (mask === void 0) { mask = -1; }
  7420. // create an empty promise
  7421. var p = Promise.resolve(eventData);
  7422. // no observers? return this promise.
  7423. if (!this._observers.length) {
  7424. return p;
  7425. }
  7426. var state = this._eventState;
  7427. state.mask = mask;
  7428. state.target = target;
  7429. state.currentTarget = currentTarget;
  7430. state.skipNextObservers = false;
  7431. // execute one callback after another (not using Promise.all, the order is important)
  7432. this._observers.forEach(function (obs) {
  7433. if (state.skipNextObservers) {
  7434. return;
  7435. }
  7436. if (obs._willBeUnregistered) {
  7437. return;
  7438. }
  7439. if (obs.mask & mask) {
  7440. if (obs.scope) {
  7441. p = p.then(function (lastReturnedValue) {
  7442. state.lastReturnValue = lastReturnedValue;
  7443. return obs.callback.apply(obs.scope, [eventData, state]);
  7444. });
  7445. }
  7446. else {
  7447. p = p.then(function (lastReturnedValue) {
  7448. state.lastReturnValue = lastReturnedValue;
  7449. return obs.callback(eventData, state);
  7450. });
  7451. }
  7452. if (obs.unregisterOnNextCall) {
  7453. _this._deferUnregister(obs);
  7454. }
  7455. }
  7456. });
  7457. // return the eventData
  7458. return p.then(function () { return eventData; });
  7459. };
  7460. /**
  7461. * Notify a specific observer
  7462. * @param observer defines the observer to notify
  7463. * @param eventData defines the data to be sent to each callback
  7464. * @param mask is used to filter observers defaults to -1
  7465. */
  7466. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7467. if (mask === void 0) { mask = -1; }
  7468. var state = this._eventState;
  7469. state.mask = mask;
  7470. state.skipNextObservers = false;
  7471. observer.callback(eventData, state);
  7472. };
  7473. /**
  7474. * Gets a boolean indicating if the observable has at least one observer
  7475. * @returns true is the Observable has at least one Observer registered
  7476. */
  7477. Observable.prototype.hasObservers = function () {
  7478. return this._observers.length > 0;
  7479. };
  7480. /**
  7481. * Clear the list of observers
  7482. */
  7483. Observable.prototype.clear = function () {
  7484. this._observers = new Array();
  7485. this._onObserverAdded = null;
  7486. };
  7487. /**
  7488. * Clone the current observable
  7489. * @returns a new observable
  7490. */
  7491. Observable.prototype.clone = function () {
  7492. var result = new Observable();
  7493. result._observers = this._observers.slice(0);
  7494. return result;
  7495. };
  7496. /**
  7497. * Does this observable handles observer registered with a given mask
  7498. * @param mask defines the mask to be tested
  7499. * @return whether or not one observer registered with the given mask is handeled
  7500. **/
  7501. Observable.prototype.hasSpecificMask = function (mask) {
  7502. if (mask === void 0) { mask = -1; }
  7503. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7504. var obs = _a[_i];
  7505. if (obs.mask & mask || obs.mask === mask) {
  7506. return true;
  7507. }
  7508. }
  7509. return false;
  7510. };
  7511. return Observable;
  7512. }());
  7513. BABYLON.Observable = Observable;
  7514. })(BABYLON || (BABYLON = {}));
  7515. //# sourceMappingURL=babylon.observable.js.map
  7516. var BABYLON;
  7517. (function (BABYLON) {
  7518. var SmartArray = /** @class */ (function () {
  7519. function SmartArray(capacity) {
  7520. this.length = 0;
  7521. this.data = new Array(capacity);
  7522. this._id = SmartArray._GlobalId++;
  7523. }
  7524. SmartArray.prototype.push = function (value) {
  7525. this.data[this.length++] = value;
  7526. if (this.length > this.data.length) {
  7527. this.data.length *= 2;
  7528. }
  7529. };
  7530. SmartArray.prototype.forEach = function (func) {
  7531. for (var index = 0; index < this.length; index++) {
  7532. func(this.data[index]);
  7533. }
  7534. };
  7535. SmartArray.prototype.sort = function (compareFn) {
  7536. this.data.sort(compareFn);
  7537. };
  7538. SmartArray.prototype.reset = function () {
  7539. this.length = 0;
  7540. };
  7541. SmartArray.prototype.dispose = function () {
  7542. this.reset();
  7543. if (this.data) {
  7544. this.data.length = 0;
  7545. this.data = [];
  7546. }
  7547. };
  7548. SmartArray.prototype.concat = function (array) {
  7549. if (array.length === 0) {
  7550. return;
  7551. }
  7552. if (this.length + array.length > this.data.length) {
  7553. this.data.length = (this.length + array.length) * 2;
  7554. }
  7555. for (var index = 0; index < array.length; index++) {
  7556. this.data[this.length++] = (array.data || array)[index];
  7557. }
  7558. };
  7559. SmartArray.prototype.indexOf = function (value) {
  7560. var position = this.data.indexOf(value);
  7561. if (position >= this.length) {
  7562. return -1;
  7563. }
  7564. return position;
  7565. };
  7566. SmartArray.prototype.contains = function (value) {
  7567. return this.data.indexOf(value) !== -1;
  7568. };
  7569. // Statics
  7570. SmartArray._GlobalId = 0;
  7571. return SmartArray;
  7572. }());
  7573. BABYLON.SmartArray = SmartArray;
  7574. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7575. __extends(SmartArrayNoDuplicate, _super);
  7576. function SmartArrayNoDuplicate() {
  7577. var _this = _super !== null && _super.apply(this, arguments) || this;
  7578. _this._duplicateId = 0;
  7579. return _this;
  7580. }
  7581. SmartArrayNoDuplicate.prototype.push = function (value) {
  7582. _super.prototype.push.call(this, value);
  7583. if (!value.__smartArrayFlags) {
  7584. value.__smartArrayFlags = {};
  7585. }
  7586. value.__smartArrayFlags[this._id] = this._duplicateId;
  7587. };
  7588. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7589. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7590. return false;
  7591. }
  7592. this.push(value);
  7593. return true;
  7594. };
  7595. SmartArrayNoDuplicate.prototype.reset = function () {
  7596. _super.prototype.reset.call(this);
  7597. this._duplicateId++;
  7598. };
  7599. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7600. if (array.length === 0) {
  7601. return;
  7602. }
  7603. if (this.length + array.length > this.data.length) {
  7604. this.data.length = (this.length + array.length) * 2;
  7605. }
  7606. for (var index = 0; index < array.length; index++) {
  7607. var item = (array.data || array)[index];
  7608. this.pushNoDuplicate(item);
  7609. }
  7610. };
  7611. return SmartArrayNoDuplicate;
  7612. }(SmartArray));
  7613. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7614. })(BABYLON || (BABYLON = {}));
  7615. //# sourceMappingURL=babylon.smartArray.js.map
  7616. var BABYLON;
  7617. (function (BABYLON) {
  7618. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7619. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7620. var LoadFileError = /** @class */ (function (_super) {
  7621. __extends(LoadFileError, _super);
  7622. function LoadFileError(message, request) {
  7623. var _this = _super.call(this, message) || this;
  7624. _this.request = request;
  7625. _this.name = "LoadFileError";
  7626. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7627. return _this;
  7628. }
  7629. // Polyfill for Object.setPrototypeOf if necessary.
  7630. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7631. return LoadFileError;
  7632. }(Error));
  7633. BABYLON.LoadFileError = LoadFileError;
  7634. var RetryStrategy = /** @class */ (function () {
  7635. function RetryStrategy() {
  7636. }
  7637. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7638. if (maxRetries === void 0) { maxRetries = 3; }
  7639. if (baseInterval === void 0) { baseInterval = 500; }
  7640. return function (url, request, retryIndex) {
  7641. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7642. return -1;
  7643. }
  7644. return Math.pow(2, retryIndex) * baseInterval;
  7645. };
  7646. };
  7647. return RetryStrategy;
  7648. }());
  7649. BABYLON.RetryStrategy = RetryStrategy;
  7650. // Screenshots
  7651. var screenshotCanvas;
  7652. var cloneValue = function (source, destinationObject) {
  7653. if (!source)
  7654. return null;
  7655. if (source instanceof BABYLON.Mesh) {
  7656. return null;
  7657. }
  7658. if (source instanceof BABYLON.SubMesh) {
  7659. return source.clone(destinationObject);
  7660. }
  7661. else if (source.clone) {
  7662. return source.clone();
  7663. }
  7664. return null;
  7665. };
  7666. var Tools = /** @class */ (function () {
  7667. function Tools() {
  7668. }
  7669. /**
  7670. * Interpolates between a and b via alpha
  7671. * @param a The lower value (returned when alpha = 0)
  7672. * @param b The upper value (returned when alpha = 1)
  7673. * @param alpha The interpolation-factor
  7674. * @return The mixed value
  7675. */
  7676. Tools.Mix = function (a, b, alpha) {
  7677. return a * (1 - alpha) + b * alpha;
  7678. };
  7679. Tools.Instantiate = function (className) {
  7680. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7681. return Tools.RegisteredExternalClasses[className];
  7682. }
  7683. var arr = className.split(".");
  7684. var fn = (window || this);
  7685. for (var i = 0, len = arr.length; i < len; i++) {
  7686. fn = fn[arr[i]];
  7687. }
  7688. if (typeof fn !== "function") {
  7689. return null;
  7690. }
  7691. return fn;
  7692. };
  7693. /**
  7694. * Provides a slice function that will work even on IE
  7695. * @param data defines the array to slice
  7696. * @returns the new sliced array
  7697. */
  7698. Tools.Slice = function (data) {
  7699. if (data.slice) {
  7700. return data.slice();
  7701. }
  7702. return Array.prototype.slice.call(data);
  7703. };
  7704. Tools.SetImmediate = function (action) {
  7705. if (window.setImmediate) {
  7706. window.setImmediate(action);
  7707. }
  7708. else {
  7709. setTimeout(action, 1);
  7710. }
  7711. };
  7712. Tools.IsExponentOfTwo = function (value) {
  7713. var count = 1;
  7714. do {
  7715. count *= 2;
  7716. } while (count < value);
  7717. return count === value;
  7718. };
  7719. /**
  7720. * Find the next highest power of two.
  7721. * @param x Number to start search from.
  7722. * @return Next highest power of two.
  7723. */
  7724. Tools.CeilingPOT = function (x) {
  7725. x--;
  7726. x |= x >> 1;
  7727. x |= x >> 2;
  7728. x |= x >> 4;
  7729. x |= x >> 8;
  7730. x |= x >> 16;
  7731. x++;
  7732. return x;
  7733. };
  7734. /**
  7735. * Find the next lowest power of two.
  7736. * @param x Number to start search from.
  7737. * @return Next lowest power of two.
  7738. */
  7739. Tools.FloorPOT = function (x) {
  7740. x = x | (x >> 1);
  7741. x = x | (x >> 2);
  7742. x = x | (x >> 4);
  7743. x = x | (x >> 8);
  7744. x = x | (x >> 16);
  7745. return x - (x >> 1);
  7746. };
  7747. /**
  7748. * Find the nearest power of two.
  7749. * @param x Number to start search from.
  7750. * @return Next nearest power of two.
  7751. */
  7752. Tools.NearestPOT = function (x) {
  7753. var c = Tools.CeilingPOT(x);
  7754. var f = Tools.FloorPOT(x);
  7755. return (c - x) > (x - f) ? f : c;
  7756. };
  7757. Tools.GetExponentOfTwo = function (value, max, mode) {
  7758. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7759. var pot;
  7760. switch (mode) {
  7761. case BABYLON.Engine.SCALEMODE_FLOOR:
  7762. pot = Tools.FloorPOT(value);
  7763. break;
  7764. case BABYLON.Engine.SCALEMODE_NEAREST:
  7765. pot = Tools.NearestPOT(value);
  7766. break;
  7767. case BABYLON.Engine.SCALEMODE_CEILING:
  7768. default:
  7769. pot = Tools.CeilingPOT(value);
  7770. break;
  7771. }
  7772. return Math.min(pot, max);
  7773. };
  7774. Tools.GetFilename = function (path) {
  7775. var index = path.lastIndexOf("/");
  7776. if (index < 0)
  7777. return path;
  7778. return path.substring(index + 1);
  7779. };
  7780. /**
  7781. * Extracts the "folder" part of a path (everything before the filename).
  7782. * @param uri The URI to extract the info from
  7783. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7784. * @returns The "folder" part of the path
  7785. */
  7786. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7787. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7788. var index = uri.lastIndexOf("/");
  7789. if (index < 0) {
  7790. if (returnUnchangedIfNoSlash) {
  7791. return uri;
  7792. }
  7793. return "";
  7794. }
  7795. return uri.substring(0, index + 1);
  7796. };
  7797. Tools.GetDOMTextContent = function (element) {
  7798. var result = "";
  7799. var child = element.firstChild;
  7800. while (child) {
  7801. if (child.nodeType === 3) {
  7802. result += child.textContent;
  7803. }
  7804. child = child.nextSibling;
  7805. }
  7806. return result;
  7807. };
  7808. Tools.ToDegrees = function (angle) {
  7809. return angle * 180 / Math.PI;
  7810. };
  7811. Tools.ToRadians = function (angle) {
  7812. return angle * Math.PI / 180;
  7813. };
  7814. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7815. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7816. var output = "";
  7817. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7818. var i = 0;
  7819. var bytes = new Uint8Array(buffer);
  7820. while (i < bytes.length) {
  7821. chr1 = bytes[i++];
  7822. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7823. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7824. enc1 = chr1 >> 2;
  7825. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7826. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7827. enc4 = chr3 & 63;
  7828. if (isNaN(chr2)) {
  7829. enc3 = enc4 = 64;
  7830. }
  7831. else if (isNaN(chr3)) {
  7832. enc4 = 64;
  7833. }
  7834. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7835. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7836. }
  7837. return "data:image/png;base64," + output;
  7838. };
  7839. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7840. if (bias === void 0) { bias = null; }
  7841. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7842. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7843. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7844. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7845. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7846. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7847. }
  7848. if (bias) {
  7849. minimum.x -= minimum.x * bias.x + bias.y;
  7850. minimum.y -= minimum.y * bias.x + bias.y;
  7851. minimum.z -= minimum.z * bias.x + bias.y;
  7852. maximum.x += maximum.x * bias.x + bias.y;
  7853. maximum.y += maximum.y * bias.x + bias.y;
  7854. maximum.z += maximum.z * bias.x + bias.y;
  7855. }
  7856. return {
  7857. minimum: minimum,
  7858. maximum: maximum
  7859. };
  7860. };
  7861. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7862. if (bias === void 0) { bias = null; }
  7863. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7864. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7865. if (!stride) {
  7866. stride = 3;
  7867. }
  7868. for (var index = start; index < start + count; index++) {
  7869. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7870. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7871. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7872. }
  7873. if (bias) {
  7874. minimum.x -= minimum.x * bias.x + bias.y;
  7875. minimum.y -= minimum.y * bias.x + bias.y;
  7876. minimum.z -= minimum.z * bias.x + bias.y;
  7877. maximum.x += maximum.x * bias.x + bias.y;
  7878. maximum.y += maximum.y * bias.x + bias.y;
  7879. maximum.z += maximum.z * bias.x + bias.y;
  7880. }
  7881. return {
  7882. minimum: minimum,
  7883. maximum: maximum
  7884. };
  7885. };
  7886. Tools.Vector2ArrayFeeder = function (array) {
  7887. return function (index) {
  7888. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7889. var length = isFloatArray ? array.length / 2 : array.length;
  7890. if (index >= length) {
  7891. return null;
  7892. }
  7893. if (isFloatArray) {
  7894. var fa = array;
  7895. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7896. }
  7897. var a = array;
  7898. return a[index];
  7899. };
  7900. };
  7901. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7902. if (bias === void 0) { bias = null; }
  7903. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7904. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7905. var i = 0;
  7906. var cur = feeder(i++);
  7907. while (cur) {
  7908. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7909. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7910. cur = feeder(i++);
  7911. }
  7912. if (bias) {
  7913. minimum.x -= minimum.x * bias.x + bias.y;
  7914. minimum.y -= minimum.y * bias.x + bias.y;
  7915. maximum.x += maximum.x * bias.x + bias.y;
  7916. maximum.y += maximum.y * bias.x + bias.y;
  7917. }
  7918. return {
  7919. minimum: minimum,
  7920. maximum: maximum
  7921. };
  7922. };
  7923. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7924. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7925. return null;
  7926. return Array.isArray(obj) ? obj : [obj];
  7927. };
  7928. // Misc.
  7929. Tools.GetPointerPrefix = function () {
  7930. var eventPrefix = "pointer";
  7931. // Check if pointer events are supported
  7932. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7933. eventPrefix = "mouse";
  7934. }
  7935. return eventPrefix;
  7936. };
  7937. /**
  7938. * @param func - the function to be called
  7939. * @param requester - the object that will request the next frame. Falls back to window.
  7940. */
  7941. Tools.QueueNewFrame = function (func, requester) {
  7942. if (!Tools.IsWindowObjectExist()) {
  7943. return setTimeout(func, 16);
  7944. }
  7945. if (!requester) {
  7946. requester = window;
  7947. }
  7948. if (requester.requestAnimationFrame) {
  7949. return requester.requestAnimationFrame(func);
  7950. }
  7951. else if (requester.msRequestAnimationFrame) {
  7952. return requester.msRequestAnimationFrame(func);
  7953. }
  7954. else if (requester.webkitRequestAnimationFrame) {
  7955. return requester.webkitRequestAnimationFrame(func);
  7956. }
  7957. else if (requester.mozRequestAnimationFrame) {
  7958. return requester.mozRequestAnimationFrame(func);
  7959. }
  7960. else if (requester.oRequestAnimationFrame) {
  7961. return requester.oRequestAnimationFrame(func);
  7962. }
  7963. else {
  7964. return window.setTimeout(func, 16);
  7965. }
  7966. };
  7967. Tools.RequestFullscreen = function (element) {
  7968. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7969. if (!requestFunction)
  7970. return;
  7971. requestFunction.call(element);
  7972. };
  7973. Tools.ExitFullscreen = function () {
  7974. if (document.exitFullscreen) {
  7975. document.exitFullscreen();
  7976. }
  7977. else if (document.mozCancelFullScreen) {
  7978. document.mozCancelFullScreen();
  7979. }
  7980. else if (document.webkitCancelFullScreen) {
  7981. document.webkitCancelFullScreen();
  7982. }
  7983. else if (document.msCancelFullScreen) {
  7984. document.msCancelFullScreen();
  7985. }
  7986. };
  7987. Tools.SetCorsBehavior = function (url, element) {
  7988. if (url && url.indexOf("data:") === 0) {
  7989. return;
  7990. }
  7991. if (Tools.CorsBehavior) {
  7992. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7993. element.crossOrigin = Tools.CorsBehavior;
  7994. }
  7995. else {
  7996. var result = Tools.CorsBehavior(url);
  7997. if (result) {
  7998. element.crossOrigin = result;
  7999. }
  8000. }
  8001. }
  8002. };
  8003. // External files
  8004. Tools.CleanUrl = function (url) {
  8005. url = url.replace(/#/mg, "%23");
  8006. return url;
  8007. };
  8008. Tools.LoadImage = function (url, onLoad, onError, database) {
  8009. if (url instanceof ArrayBuffer) {
  8010. url = Tools.EncodeArrayBufferTobase64(url);
  8011. }
  8012. url = Tools.CleanUrl(url);
  8013. url = Tools.PreprocessUrl(url);
  8014. var img = new Image();
  8015. Tools.SetCorsBehavior(url, img);
  8016. img.onload = function () {
  8017. onLoad(img);
  8018. };
  8019. img.onerror = function (err) {
  8020. Tools.Error("Error while trying to load image: " + url);
  8021. if (onError) {
  8022. onError("Error while trying to load image: " + url, err);
  8023. }
  8024. };
  8025. var noIndexedDB = function () {
  8026. img.src = url;
  8027. };
  8028. var loadFromIndexedDB = function () {
  8029. if (database) {
  8030. database.loadImageFromDB(url, img);
  8031. }
  8032. };
  8033. //ANY database to do!
  8034. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8035. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8036. }
  8037. else {
  8038. if (url.indexOf("file:") !== -1) {
  8039. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8040. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8041. try {
  8042. var blobURL;
  8043. try {
  8044. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8045. }
  8046. catch (ex) {
  8047. // Chrome doesn't support oneTimeOnly parameter
  8048. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8049. }
  8050. img.src = blobURL;
  8051. }
  8052. catch (e) {
  8053. img.src = "";
  8054. }
  8055. return img;
  8056. }
  8057. }
  8058. noIndexedDB();
  8059. }
  8060. return img;
  8061. };
  8062. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8063. url = Tools.CleanUrl(url);
  8064. url = Tools.PreprocessUrl(url);
  8065. // If file and file input are set
  8066. if (url.indexOf("file:") !== -1) {
  8067. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8068. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8069. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8070. }
  8071. }
  8072. var loadUrl = Tools.BaseUrl + url;
  8073. var aborted = false;
  8074. var fileRequest = {
  8075. onCompleteObservable: new BABYLON.Observable(),
  8076. abort: function () { return aborted = true; },
  8077. };
  8078. var requestFile = function () {
  8079. var request = new XMLHttpRequest();
  8080. var retryHandle = null;
  8081. fileRequest.abort = function () {
  8082. aborted = true;
  8083. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8084. request.abort();
  8085. }
  8086. if (retryHandle !== null) {
  8087. clearTimeout(retryHandle);
  8088. retryHandle = null;
  8089. }
  8090. };
  8091. var retryLoop = function (retryIndex) {
  8092. request.open('GET', loadUrl, true);
  8093. if (useArrayBuffer) {
  8094. request.responseType = "arraybuffer";
  8095. }
  8096. if (onProgress) {
  8097. request.addEventListener("progress", onProgress);
  8098. }
  8099. var onLoadEnd = function () {
  8100. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8101. };
  8102. request.addEventListener("loadend", onLoadEnd);
  8103. var onReadyStateChange = function () {
  8104. if (aborted) {
  8105. return;
  8106. }
  8107. // In case of undefined state in some browsers.
  8108. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8109. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8110. request.removeEventListener("readystatechange", onReadyStateChange);
  8111. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8112. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8113. return;
  8114. }
  8115. var retryStrategy = Tools.DefaultRetryStrategy;
  8116. if (retryStrategy) {
  8117. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8118. if (waitTime !== -1) {
  8119. // Prevent the request from completing for retry.
  8120. request.removeEventListener("loadend", onLoadEnd);
  8121. request = new XMLHttpRequest();
  8122. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8123. return;
  8124. }
  8125. }
  8126. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8127. if (onError) {
  8128. onError(request, e);
  8129. }
  8130. else {
  8131. throw e;
  8132. }
  8133. }
  8134. };
  8135. request.addEventListener("readystatechange", onReadyStateChange);
  8136. request.send();
  8137. };
  8138. retryLoop(0);
  8139. };
  8140. // Caching all files
  8141. if (database && database.enableSceneOffline) {
  8142. var noIndexedDB_1 = function () {
  8143. if (!aborted) {
  8144. requestFile();
  8145. }
  8146. };
  8147. var loadFromIndexedDB = function () {
  8148. // TODO: database needs to support aborting and should return a IFileRequest
  8149. if (aborted) {
  8150. return;
  8151. }
  8152. if (database) {
  8153. database.loadFileFromDB(url, function (data) {
  8154. if (!aborted) {
  8155. onSuccess(data);
  8156. }
  8157. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8158. }, onProgress ? function (event) {
  8159. if (!aborted) {
  8160. onProgress(event);
  8161. }
  8162. } : undefined, noIndexedDB_1, useArrayBuffer);
  8163. }
  8164. };
  8165. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8166. }
  8167. else {
  8168. requestFile();
  8169. }
  8170. return fileRequest;
  8171. };
  8172. /**
  8173. * Load a script (identified by an url). When the url returns, the
  8174. * content of this file is added into a new script element, attached to the DOM (body element)
  8175. */
  8176. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8177. var head = document.getElementsByTagName('head')[0];
  8178. var script = document.createElement('script');
  8179. script.type = 'text/javascript';
  8180. script.src = scriptUrl;
  8181. script.onload = function () {
  8182. if (onSuccess) {
  8183. onSuccess();
  8184. }
  8185. };
  8186. script.onerror = function (e) {
  8187. if (onError) {
  8188. onError("Unable to load script", e);
  8189. }
  8190. };
  8191. head.appendChild(script);
  8192. };
  8193. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8194. var reader = new FileReader();
  8195. var request = {
  8196. onCompleteObservable: new BABYLON.Observable(),
  8197. abort: function () { return reader.abort(); },
  8198. };
  8199. reader.onloadend = function (e) {
  8200. request.onCompleteObservable.notifyObservers(request);
  8201. };
  8202. reader.onload = function (e) {
  8203. //target doesn't have result from ts 1.3
  8204. callback(e.target['result']);
  8205. };
  8206. reader.onprogress = progressCallback;
  8207. reader.readAsDataURL(fileToLoad);
  8208. return request;
  8209. };
  8210. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8211. var reader = new FileReader();
  8212. var request = {
  8213. onCompleteObservable: new BABYLON.Observable(),
  8214. abort: function () { return reader.abort(); },
  8215. };
  8216. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8217. reader.onerror = function (e) {
  8218. Tools.Log("Error while reading file: " + fileToLoad.name);
  8219. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8220. };
  8221. reader.onload = function (e) {
  8222. //target doesn't have result from ts 1.3
  8223. callback(e.target['result']);
  8224. };
  8225. if (progressCallBack) {
  8226. reader.onprogress = progressCallBack;
  8227. }
  8228. if (!useArrayBuffer) {
  8229. // Asynchronous read
  8230. reader.readAsText(fileToLoad);
  8231. }
  8232. else {
  8233. reader.readAsArrayBuffer(fileToLoad);
  8234. }
  8235. return request;
  8236. };
  8237. //returns a downloadable url to a file content.
  8238. Tools.FileAsURL = function (content) {
  8239. var fileBlob = new Blob([content]);
  8240. var url = window.URL || window.webkitURL;
  8241. var link = url.createObjectURL(fileBlob);
  8242. return link;
  8243. };
  8244. // Misc.
  8245. Tools.Format = function (value, decimals) {
  8246. if (decimals === void 0) { decimals = 2; }
  8247. return value.toFixed(decimals);
  8248. };
  8249. Tools.CheckExtends = function (v, min, max) {
  8250. if (v.x < min.x)
  8251. min.x = v.x;
  8252. if (v.y < min.y)
  8253. min.y = v.y;
  8254. if (v.z < min.z)
  8255. min.z = v.z;
  8256. if (v.x > max.x)
  8257. max.x = v.x;
  8258. if (v.y > max.y)
  8259. max.y = v.y;
  8260. if (v.z > max.z)
  8261. max.z = v.z;
  8262. };
  8263. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8264. for (var prop in source) {
  8265. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8266. continue;
  8267. }
  8268. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8269. continue;
  8270. }
  8271. var sourceValue = source[prop];
  8272. var typeOfSourceValue = typeof sourceValue;
  8273. if (typeOfSourceValue === "function") {
  8274. continue;
  8275. }
  8276. if (typeOfSourceValue === "object") {
  8277. if (sourceValue instanceof Array) {
  8278. destination[prop] = [];
  8279. if (sourceValue.length > 0) {
  8280. if (typeof sourceValue[0] == "object") {
  8281. for (var index = 0; index < sourceValue.length; index++) {
  8282. var clonedValue = cloneValue(sourceValue[index], destination);
  8283. if (destination[prop].indexOf(clonedValue) === -1) {
  8284. destination[prop].push(clonedValue);
  8285. }
  8286. }
  8287. }
  8288. else {
  8289. destination[prop] = sourceValue.slice(0);
  8290. }
  8291. }
  8292. }
  8293. else {
  8294. destination[prop] = cloneValue(sourceValue, destination);
  8295. }
  8296. }
  8297. else {
  8298. destination[prop] = sourceValue;
  8299. }
  8300. }
  8301. };
  8302. Tools.IsEmpty = function (obj) {
  8303. for (var i in obj) {
  8304. if (obj.hasOwnProperty(i)) {
  8305. return false;
  8306. }
  8307. }
  8308. return true;
  8309. };
  8310. Tools.RegisterTopRootEvents = function (events) {
  8311. for (var index = 0; index < events.length; index++) {
  8312. var event = events[index];
  8313. window.addEventListener(event.name, event.handler, false);
  8314. try {
  8315. if (window.parent) {
  8316. window.parent.addEventListener(event.name, event.handler, false);
  8317. }
  8318. }
  8319. catch (e) {
  8320. // Silently fails...
  8321. }
  8322. }
  8323. };
  8324. Tools.UnregisterTopRootEvents = function (events) {
  8325. for (var index = 0; index < events.length; index++) {
  8326. var event = events[index];
  8327. window.removeEventListener(event.name, event.handler);
  8328. try {
  8329. if (window.parent) {
  8330. window.parent.removeEventListener(event.name, event.handler);
  8331. }
  8332. }
  8333. catch (e) {
  8334. // Silently fails...
  8335. }
  8336. }
  8337. };
  8338. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8339. if (mimeType === void 0) { mimeType = "image/png"; }
  8340. // Read the contents of the framebuffer
  8341. var numberOfChannelsByLine = width * 4;
  8342. var halfHeight = height / 2;
  8343. //Reading datas from WebGL
  8344. var data = engine.readPixels(0, 0, width, height);
  8345. //To flip image on Y axis.
  8346. for (var i = 0; i < halfHeight; i++) {
  8347. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8348. var currentCell = j + i * numberOfChannelsByLine;
  8349. var targetLine = height - i - 1;
  8350. var targetCell = j + targetLine * numberOfChannelsByLine;
  8351. var temp = data[currentCell];
  8352. data[currentCell] = data[targetCell];
  8353. data[targetCell] = temp;
  8354. }
  8355. }
  8356. // Create a 2D canvas to store the result
  8357. if (!screenshotCanvas) {
  8358. screenshotCanvas = document.createElement('canvas');
  8359. }
  8360. screenshotCanvas.width = width;
  8361. screenshotCanvas.height = height;
  8362. var context = screenshotCanvas.getContext('2d');
  8363. if (context) {
  8364. // Copy the pixels to a 2D canvas
  8365. var imageData = context.createImageData(width, height);
  8366. var castData = (imageData.data);
  8367. castData.set(data);
  8368. context.putImageData(imageData, 0, 0);
  8369. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8370. }
  8371. };
  8372. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8373. if (mimeType === void 0) { mimeType = "image/png"; }
  8374. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8375. if (successCallback) {
  8376. successCallback(base64Image);
  8377. }
  8378. else {
  8379. // We need HTMLCanvasElement.toBlob for HD screenshots
  8380. if (!screenshotCanvas.toBlob) {
  8381. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8382. screenshotCanvas.toBlob = function (callback, type, quality) {
  8383. var _this = this;
  8384. setTimeout(function () {
  8385. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8386. for (var i = 0; i < len; i++) {
  8387. arr[i] = binStr.charCodeAt(i);
  8388. }
  8389. callback(new Blob([arr], { type: type || 'image/png' }));
  8390. });
  8391. };
  8392. }
  8393. screenshotCanvas.toBlob(function (blob) {
  8394. var url = URL.createObjectURL(blob);
  8395. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8396. if (("download" in document.createElement("a"))) {
  8397. var a = window.document.createElement("a");
  8398. a.href = url;
  8399. if (fileName) {
  8400. a.setAttribute("download", fileName);
  8401. }
  8402. else {
  8403. var date = new Date();
  8404. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8405. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8406. }
  8407. window.document.body.appendChild(a);
  8408. a.addEventListener("click", function () {
  8409. if (a.parentElement) {
  8410. a.parentElement.removeChild(a);
  8411. }
  8412. });
  8413. a.click();
  8414. }
  8415. else {
  8416. var newWindow = window.open("");
  8417. if (!newWindow)
  8418. return;
  8419. var img = newWindow.document.createElement("img");
  8420. img.onload = function () {
  8421. // no longer need to read the blob so it's revoked
  8422. URL.revokeObjectURL(url);
  8423. };
  8424. img.src = url;
  8425. newWindow.document.body.appendChild(img);
  8426. }
  8427. });
  8428. }
  8429. };
  8430. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8431. if (mimeType === void 0) { mimeType = "image/png"; }
  8432. var width;
  8433. var height;
  8434. // If a precision value is specified
  8435. if (size.precision) {
  8436. width = Math.round(engine.getRenderWidth() * size.precision);
  8437. height = Math.round(width / engine.getAspectRatio(camera));
  8438. }
  8439. else if (size.width && size.height) {
  8440. width = size.width;
  8441. height = size.height;
  8442. }
  8443. else if (size.width && !size.height) {
  8444. width = size.width;
  8445. height = Math.round(width / engine.getAspectRatio(camera));
  8446. }
  8447. else if (size.height && !size.width) {
  8448. height = size.height;
  8449. width = Math.round(height * engine.getAspectRatio(camera));
  8450. }
  8451. else if (!isNaN(size)) {
  8452. height = size;
  8453. width = size;
  8454. }
  8455. else {
  8456. Tools.Error("Invalid 'size' parameter !");
  8457. return;
  8458. }
  8459. if (!screenshotCanvas) {
  8460. screenshotCanvas = document.createElement('canvas');
  8461. }
  8462. screenshotCanvas.width = width;
  8463. screenshotCanvas.height = height;
  8464. var renderContext = screenshotCanvas.getContext("2d");
  8465. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8466. var newWidth = width;
  8467. var newHeight = newWidth / ratio;
  8468. if (newHeight > height) {
  8469. newHeight = height;
  8470. newWidth = newHeight * ratio;
  8471. }
  8472. var offsetX = Math.max(0, width - newWidth) / 2;
  8473. var offsetY = Math.max(0, height - newHeight) / 2;
  8474. var renderingCanvas = engine.getRenderingCanvas();
  8475. if (renderContext && renderingCanvas) {
  8476. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8477. }
  8478. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8479. };
  8480. /**
  8481. * Generates an image screenshot from the specified camera.
  8482. *
  8483. * @param engine The engine to use for rendering
  8484. * @param camera The camera to use for rendering
  8485. * @param size This parameter can be set to a single number or to an object with the
  8486. * following (optional) properties: precision, width, height. If a single number is passed,
  8487. * it will be used for both width and height. If an object is passed, the screenshot size
  8488. * will be derived from the parameters. The precision property is a multiplier allowing
  8489. * rendering at a higher or lower resolution.
  8490. * @param successCallback The callback receives a single parameter which contains the
  8491. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8492. * src parameter of an <img> to display it.
  8493. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8494. * Check your browser for supported MIME types.
  8495. * @param samples Texture samples (default: 1)
  8496. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8497. * @param fileName A name for for the downloaded file.
  8498. * @constructor
  8499. */
  8500. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8501. if (mimeType === void 0) { mimeType = "image/png"; }
  8502. if (samples === void 0) { samples = 1; }
  8503. if (antialiasing === void 0) { antialiasing = false; }
  8504. var width;
  8505. var height;
  8506. //If a precision value is specified
  8507. if (size.precision) {
  8508. width = Math.round(engine.getRenderWidth() * size.precision);
  8509. height = Math.round(width / engine.getAspectRatio(camera));
  8510. size = { width: width, height: height };
  8511. }
  8512. else if (size.width && size.height) {
  8513. width = size.width;
  8514. height = size.height;
  8515. }
  8516. else if (size.width && !size.height) {
  8517. width = size.width;
  8518. height = Math.round(width / engine.getAspectRatio(camera));
  8519. size = { width: width, height: height };
  8520. }
  8521. else if (size.height && !size.width) {
  8522. height = size.height;
  8523. width = Math.round(height * engine.getAspectRatio(camera));
  8524. size = { width: width, height: height };
  8525. }
  8526. else if (!isNaN(size)) {
  8527. height = size;
  8528. width = size;
  8529. }
  8530. else {
  8531. Tools.Error("Invalid 'size' parameter !");
  8532. return;
  8533. }
  8534. var scene = camera.getScene();
  8535. var previousCamera = null;
  8536. if (scene.activeCamera !== camera) {
  8537. previousCamera = scene.activeCamera;
  8538. scene.activeCamera = camera;
  8539. }
  8540. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8541. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8542. texture.renderList = null;
  8543. texture.samples = samples;
  8544. if (antialiasing) {
  8545. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8546. }
  8547. texture.onAfterRenderObservable.add(function () {
  8548. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8549. });
  8550. scene.incrementRenderId();
  8551. scene.resetCachedMaterial();
  8552. texture.render(true);
  8553. texture.dispose();
  8554. if (previousCamera) {
  8555. scene.activeCamera = previousCamera;
  8556. }
  8557. camera.getProjectionMatrix(true); // Force cache refresh;
  8558. };
  8559. // XHR response validator for local file scenario
  8560. Tools.ValidateXHRData = function (xhr, dataType) {
  8561. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8562. if (dataType === void 0) { dataType = 7; }
  8563. try {
  8564. if (dataType & 1) {
  8565. if (xhr.responseText && xhr.responseText.length > 0) {
  8566. return true;
  8567. }
  8568. else if (dataType === 1) {
  8569. return false;
  8570. }
  8571. }
  8572. if (dataType & 2) {
  8573. // Check header width and height since there is no "TGA" magic number
  8574. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8575. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8576. return true;
  8577. }
  8578. else if (dataType === 2) {
  8579. return false;
  8580. }
  8581. }
  8582. if (dataType & 4) {
  8583. // Check for the "DDS" magic number
  8584. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8585. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8586. return true;
  8587. }
  8588. else {
  8589. return false;
  8590. }
  8591. }
  8592. }
  8593. catch (e) {
  8594. // Global protection
  8595. }
  8596. return false;
  8597. };
  8598. /**
  8599. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8600. * Be aware Math.random() could cause collisions, but:
  8601. * "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"
  8602. */
  8603. Tools.RandomId = function () {
  8604. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8605. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8606. return v.toString(16);
  8607. });
  8608. };
  8609. /**
  8610. * Test if the given uri is a base64 string.
  8611. * @param uri The uri to test
  8612. * @return True if the uri is a base64 string or false otherwise.
  8613. */
  8614. Tools.IsBase64 = function (uri) {
  8615. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8616. };
  8617. /**
  8618. * Decode the given base64 uri.
  8619. * @param uri The uri to decode
  8620. * @return The decoded base64 data.
  8621. */
  8622. Tools.DecodeBase64 = function (uri) {
  8623. var decodedString = atob(uri.split(",")[1]);
  8624. var bufferLength = decodedString.length;
  8625. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8626. for (var i = 0; i < bufferLength; i++) {
  8627. bufferView[i] = decodedString.charCodeAt(i);
  8628. }
  8629. return bufferView.buffer;
  8630. };
  8631. Object.defineProperty(Tools, "NoneLogLevel", {
  8632. get: function () {
  8633. return Tools._NoneLogLevel;
  8634. },
  8635. enumerable: true,
  8636. configurable: true
  8637. });
  8638. Object.defineProperty(Tools, "MessageLogLevel", {
  8639. get: function () {
  8640. return Tools._MessageLogLevel;
  8641. },
  8642. enumerable: true,
  8643. configurable: true
  8644. });
  8645. Object.defineProperty(Tools, "WarningLogLevel", {
  8646. get: function () {
  8647. return Tools._WarningLogLevel;
  8648. },
  8649. enumerable: true,
  8650. configurable: true
  8651. });
  8652. Object.defineProperty(Tools, "ErrorLogLevel", {
  8653. get: function () {
  8654. return Tools._ErrorLogLevel;
  8655. },
  8656. enumerable: true,
  8657. configurable: true
  8658. });
  8659. Object.defineProperty(Tools, "AllLogLevel", {
  8660. get: function () {
  8661. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8662. },
  8663. enumerable: true,
  8664. configurable: true
  8665. });
  8666. Tools._AddLogEntry = function (entry) {
  8667. Tools._LogCache = entry + Tools._LogCache;
  8668. if (Tools.OnNewCacheEntry) {
  8669. Tools.OnNewCacheEntry(entry);
  8670. }
  8671. };
  8672. Tools._FormatMessage = function (message) {
  8673. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8674. var date = new Date();
  8675. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8676. };
  8677. Tools._LogDisabled = function (message) {
  8678. // nothing to do
  8679. };
  8680. Tools._LogEnabled = function (message) {
  8681. var formattedMessage = Tools._FormatMessage(message);
  8682. console.log("BJS - " + formattedMessage);
  8683. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8684. Tools._AddLogEntry(entry);
  8685. };
  8686. Tools._WarnDisabled = function (message) {
  8687. // nothing to do
  8688. };
  8689. Tools._WarnEnabled = function (message) {
  8690. var formattedMessage = Tools._FormatMessage(message);
  8691. console.warn("BJS - " + formattedMessage);
  8692. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8693. Tools._AddLogEntry(entry);
  8694. };
  8695. Tools._ErrorDisabled = function (message) {
  8696. // nothing to do
  8697. };
  8698. Tools._ErrorEnabled = function (message) {
  8699. Tools.errorsCount++;
  8700. var formattedMessage = Tools._FormatMessage(message);
  8701. console.error("BJS - " + formattedMessage);
  8702. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8703. Tools._AddLogEntry(entry);
  8704. };
  8705. Object.defineProperty(Tools, "LogCache", {
  8706. get: function () {
  8707. return Tools._LogCache;
  8708. },
  8709. enumerable: true,
  8710. configurable: true
  8711. });
  8712. Tools.ClearLogCache = function () {
  8713. Tools._LogCache = "";
  8714. Tools.errorsCount = 0;
  8715. };
  8716. Object.defineProperty(Tools, "LogLevels", {
  8717. set: function (level) {
  8718. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8719. Tools.Log = Tools._LogEnabled;
  8720. }
  8721. else {
  8722. Tools.Log = Tools._LogDisabled;
  8723. }
  8724. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8725. Tools.Warn = Tools._WarnEnabled;
  8726. }
  8727. else {
  8728. Tools.Warn = Tools._WarnDisabled;
  8729. }
  8730. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8731. Tools.Error = Tools._ErrorEnabled;
  8732. }
  8733. else {
  8734. Tools.Error = Tools._ErrorDisabled;
  8735. }
  8736. },
  8737. enumerable: true,
  8738. configurable: true
  8739. });
  8740. Tools.IsWindowObjectExist = function () {
  8741. return (typeof window) !== "undefined";
  8742. };
  8743. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8744. get: function () {
  8745. return Tools._PerformanceNoneLogLevel;
  8746. },
  8747. enumerable: true,
  8748. configurable: true
  8749. });
  8750. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8751. get: function () {
  8752. return Tools._PerformanceUserMarkLogLevel;
  8753. },
  8754. enumerable: true,
  8755. configurable: true
  8756. });
  8757. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8758. get: function () {
  8759. return Tools._PerformanceConsoleLogLevel;
  8760. },
  8761. enumerable: true,
  8762. configurable: true
  8763. });
  8764. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8765. set: function (level) {
  8766. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8767. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8768. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8769. return;
  8770. }
  8771. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8772. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8773. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8774. return;
  8775. }
  8776. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8777. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8778. },
  8779. enumerable: true,
  8780. configurable: true
  8781. });
  8782. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8783. };
  8784. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8785. };
  8786. Tools._StartUserMark = function (counterName, condition) {
  8787. if (condition === void 0) { condition = true; }
  8788. if (!Tools._performance) {
  8789. if (!Tools.IsWindowObjectExist()) {
  8790. return;
  8791. }
  8792. Tools._performance = window.performance;
  8793. }
  8794. if (!condition || !Tools._performance.mark) {
  8795. return;
  8796. }
  8797. Tools._performance.mark(counterName + "-Begin");
  8798. };
  8799. Tools._EndUserMark = function (counterName, condition) {
  8800. if (condition === void 0) { condition = true; }
  8801. if (!condition || !Tools._performance.mark) {
  8802. return;
  8803. }
  8804. Tools._performance.mark(counterName + "-End");
  8805. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8806. };
  8807. Tools._StartPerformanceConsole = function (counterName, condition) {
  8808. if (condition === void 0) { condition = true; }
  8809. if (!condition) {
  8810. return;
  8811. }
  8812. Tools._StartUserMark(counterName, condition);
  8813. if (console.time) {
  8814. console.time(counterName);
  8815. }
  8816. };
  8817. Tools._EndPerformanceConsole = function (counterName, condition) {
  8818. if (condition === void 0) { condition = true; }
  8819. if (!condition) {
  8820. return;
  8821. }
  8822. Tools._EndUserMark(counterName, condition);
  8823. if (console.time) {
  8824. console.timeEnd(counterName);
  8825. }
  8826. };
  8827. Object.defineProperty(Tools, "Now", {
  8828. get: function () {
  8829. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8830. return window.performance.now();
  8831. }
  8832. return new Date().getTime();
  8833. },
  8834. enumerable: true,
  8835. configurable: true
  8836. });
  8837. /**
  8838. * This method will return the name of the class used to create the instance of the given object.
  8839. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8840. * @param object the object to get the class name from
  8841. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8842. */
  8843. Tools.GetClassName = function (object, isType) {
  8844. if (isType === void 0) { isType = false; }
  8845. var name = null;
  8846. if (!isType && object.getClassName) {
  8847. name = object.getClassName();
  8848. }
  8849. else {
  8850. if (object instanceof Object) {
  8851. var classObj = isType ? object : Object.getPrototypeOf(object);
  8852. name = classObj.constructor["__bjsclassName__"];
  8853. }
  8854. if (!name) {
  8855. name = typeof object;
  8856. }
  8857. }
  8858. return name;
  8859. };
  8860. Tools.First = function (array, predicate) {
  8861. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8862. var el = array_1[_i];
  8863. if (predicate(el)) {
  8864. return el;
  8865. }
  8866. }
  8867. return null;
  8868. };
  8869. /**
  8870. * This method will return the name of the full name of the class, including its owning module (if any).
  8871. * 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).
  8872. * @param object the object to get the class name from
  8873. * @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.
  8874. */
  8875. Tools.getFullClassName = function (object, isType) {
  8876. if (isType === void 0) { isType = false; }
  8877. var className = null;
  8878. var moduleName = null;
  8879. if (!isType && object.getClassName) {
  8880. className = object.getClassName();
  8881. }
  8882. else {
  8883. if (object instanceof Object) {
  8884. var classObj = isType ? object : Object.getPrototypeOf(object);
  8885. className = classObj.constructor["__bjsclassName__"];
  8886. moduleName = classObj.constructor["__bjsmoduleName__"];
  8887. }
  8888. if (!className) {
  8889. className = typeof object;
  8890. }
  8891. }
  8892. if (!className) {
  8893. return null;
  8894. }
  8895. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8896. };
  8897. /**
  8898. * 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.
  8899. * @param array
  8900. */
  8901. Tools.arrayOrStringFeeder = function (array) {
  8902. return function (index) {
  8903. if (index >= array.length) {
  8904. return null;
  8905. }
  8906. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8907. if (val && val.getHashCode) {
  8908. val = val.getHashCode();
  8909. }
  8910. if (typeof val === "string") {
  8911. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8912. }
  8913. return val;
  8914. };
  8915. };
  8916. /**
  8917. * Compute the hashCode of a stream of number
  8918. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8919. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8920. * @return the hash code computed
  8921. */
  8922. Tools.hashCodeFromStream = function (feeder) {
  8923. // Based from here: http://stackoverflow.com/a/7616484/802124
  8924. var hash = 0;
  8925. var index = 0;
  8926. var chr = feeder(index++);
  8927. while (chr != null) {
  8928. hash = ((hash << 5) - hash) + chr;
  8929. hash |= 0; // Convert to 32bit integer
  8930. chr = feeder(index++);
  8931. }
  8932. return hash;
  8933. };
  8934. /**
  8935. * Returns a promise that resolves after the given amount of time.
  8936. * @param delay Number of milliseconds to delay
  8937. * @returns Promise that resolves after the given amount of time
  8938. */
  8939. Tools.DelayAsync = function (delay) {
  8940. return new Promise(function (resolve) {
  8941. setTimeout(function () {
  8942. resolve();
  8943. }, delay);
  8944. });
  8945. };
  8946. Tools.BaseUrl = "";
  8947. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8948. /**
  8949. * Default behaviour for cors in the application.
  8950. * It can be a string if the expected behavior is identical in the entire app.
  8951. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8952. */
  8953. Tools.CorsBehavior = "anonymous";
  8954. Tools.UseFallbackTexture = true;
  8955. /**
  8956. * Use this object to register external classes like custom textures or material
  8957. * to allow the laoders to instantiate them
  8958. */
  8959. Tools.RegisteredExternalClasses = {};
  8960. // Used in case of a texture loading problem
  8961. 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";
  8962. Tools.PreprocessUrl = function (url) {
  8963. return url;
  8964. };
  8965. // Logs
  8966. Tools._NoneLogLevel = 0;
  8967. Tools._MessageLogLevel = 1;
  8968. Tools._WarningLogLevel = 2;
  8969. Tools._ErrorLogLevel = 4;
  8970. Tools._LogCache = "";
  8971. Tools.errorsCount = 0;
  8972. Tools.Log = Tools._LogEnabled;
  8973. Tools.Warn = Tools._WarnEnabled;
  8974. Tools.Error = Tools._ErrorEnabled;
  8975. // Performances
  8976. Tools._PerformanceNoneLogLevel = 0;
  8977. Tools._PerformanceUserMarkLogLevel = 1;
  8978. Tools._PerformanceConsoleLogLevel = 2;
  8979. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8980. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8981. return Tools;
  8982. }());
  8983. BABYLON.Tools = Tools;
  8984. /**
  8985. * This class is used to track a performance counter which is number based.
  8986. * The user has access to many properties which give statistics of different nature
  8987. *
  8988. * The implementer can track two kinds of Performance Counter: time and count
  8989. * 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.
  8990. * 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.
  8991. */
  8992. var PerfCounter = /** @class */ (function () {
  8993. function PerfCounter() {
  8994. this._startMonitoringTime = 0;
  8995. this._min = 0;
  8996. this._max = 0;
  8997. this._average = 0;
  8998. this._lastSecAverage = 0;
  8999. this._current = 0;
  9000. this._totalValueCount = 0;
  9001. this._totalAccumulated = 0;
  9002. this._lastSecAccumulated = 0;
  9003. this._lastSecTime = 0;
  9004. this._lastSecValueCount = 0;
  9005. }
  9006. Object.defineProperty(PerfCounter.prototype, "min", {
  9007. /**
  9008. * Returns the smallest value ever
  9009. */
  9010. get: function () {
  9011. return this._min;
  9012. },
  9013. enumerable: true,
  9014. configurable: true
  9015. });
  9016. Object.defineProperty(PerfCounter.prototype, "max", {
  9017. /**
  9018. * Returns the biggest value ever
  9019. */
  9020. get: function () {
  9021. return this._max;
  9022. },
  9023. enumerable: true,
  9024. configurable: true
  9025. });
  9026. Object.defineProperty(PerfCounter.prototype, "average", {
  9027. /**
  9028. * Returns the average value since the performance counter is running
  9029. */
  9030. get: function () {
  9031. return this._average;
  9032. },
  9033. enumerable: true,
  9034. configurable: true
  9035. });
  9036. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9037. /**
  9038. * Returns the average value of the last second the counter was monitored
  9039. */
  9040. get: function () {
  9041. return this._lastSecAverage;
  9042. },
  9043. enumerable: true,
  9044. configurable: true
  9045. });
  9046. Object.defineProperty(PerfCounter.prototype, "current", {
  9047. /**
  9048. * Returns the current value
  9049. */
  9050. get: function () {
  9051. return this._current;
  9052. },
  9053. enumerable: true,
  9054. configurable: true
  9055. });
  9056. Object.defineProperty(PerfCounter.prototype, "total", {
  9057. get: function () {
  9058. return this._totalAccumulated;
  9059. },
  9060. enumerable: true,
  9061. configurable: true
  9062. });
  9063. Object.defineProperty(PerfCounter.prototype, "count", {
  9064. get: function () {
  9065. return this._totalValueCount;
  9066. },
  9067. enumerable: true,
  9068. configurable: true
  9069. });
  9070. /**
  9071. * Call this method to start monitoring a new frame.
  9072. * 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.
  9073. */
  9074. PerfCounter.prototype.fetchNewFrame = function () {
  9075. this._totalValueCount++;
  9076. this._current = 0;
  9077. this._lastSecValueCount++;
  9078. };
  9079. /**
  9080. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9081. * @param newCount the count value to add to the monitored count
  9082. * @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.
  9083. */
  9084. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9085. if (!PerfCounter.Enabled) {
  9086. return;
  9087. }
  9088. this._current += newCount;
  9089. if (fetchResult) {
  9090. this._fetchResult();
  9091. }
  9092. };
  9093. /**
  9094. * Start monitoring this performance counter
  9095. */
  9096. PerfCounter.prototype.beginMonitoring = function () {
  9097. if (!PerfCounter.Enabled) {
  9098. return;
  9099. }
  9100. this._startMonitoringTime = Tools.Now;
  9101. };
  9102. /**
  9103. * Compute the time lapsed since the previous beginMonitoring() call.
  9104. * @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
  9105. */
  9106. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9107. if (newFrame === void 0) { newFrame = true; }
  9108. if (!PerfCounter.Enabled) {
  9109. return;
  9110. }
  9111. if (newFrame) {
  9112. this.fetchNewFrame();
  9113. }
  9114. var currentTime = Tools.Now;
  9115. this._current = currentTime - this._startMonitoringTime;
  9116. if (newFrame) {
  9117. this._fetchResult();
  9118. }
  9119. };
  9120. PerfCounter.prototype._fetchResult = function () {
  9121. this._totalAccumulated += this._current;
  9122. this._lastSecAccumulated += this._current;
  9123. // Min/Max update
  9124. this._min = Math.min(this._min, this._current);
  9125. this._max = Math.max(this._max, this._current);
  9126. this._average = this._totalAccumulated / this._totalValueCount;
  9127. // Reset last sec?
  9128. var now = Tools.Now;
  9129. if ((now - this._lastSecTime) > 1000) {
  9130. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9131. this._lastSecTime = now;
  9132. this._lastSecAccumulated = 0;
  9133. this._lastSecValueCount = 0;
  9134. }
  9135. };
  9136. PerfCounter.Enabled = true;
  9137. return PerfCounter;
  9138. }());
  9139. BABYLON.PerfCounter = PerfCounter;
  9140. /**
  9141. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9142. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9143. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9144. * @param name The name of the class, case should be preserved
  9145. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9146. */
  9147. function className(name, module) {
  9148. return function (target) {
  9149. target["__bjsclassName__"] = name;
  9150. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9151. };
  9152. }
  9153. BABYLON.className = className;
  9154. /**
  9155. * An implementation of a loop for asynchronous functions.
  9156. */
  9157. var AsyncLoop = /** @class */ (function () {
  9158. /**
  9159. * Constroctor.
  9160. * @param iterations the number of iterations.
  9161. * @param _fn the function to run each iteration
  9162. * @param _successCallback the callback that will be called upon succesful execution
  9163. * @param offset starting offset.
  9164. */
  9165. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9166. if (offset === void 0) { offset = 0; }
  9167. this.iterations = iterations;
  9168. this._fn = _fn;
  9169. this._successCallback = _successCallback;
  9170. this.index = offset - 1;
  9171. this._done = false;
  9172. }
  9173. /**
  9174. * Execute the next iteration. Must be called after the last iteration was finished.
  9175. */
  9176. AsyncLoop.prototype.executeNext = function () {
  9177. if (!this._done) {
  9178. if (this.index + 1 < this.iterations) {
  9179. ++this.index;
  9180. this._fn(this);
  9181. }
  9182. else {
  9183. this.breakLoop();
  9184. }
  9185. }
  9186. };
  9187. /**
  9188. * Break the loop and run the success callback.
  9189. */
  9190. AsyncLoop.prototype.breakLoop = function () {
  9191. this._done = true;
  9192. this._successCallback();
  9193. };
  9194. /**
  9195. * Helper function
  9196. */
  9197. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9198. if (offset === void 0) { offset = 0; }
  9199. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9200. loop.executeNext();
  9201. return loop;
  9202. };
  9203. /**
  9204. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9205. * @param iterations total number of iterations
  9206. * @param syncedIterations number of synchronous iterations in each async iteration.
  9207. * @param fn the function to call each iteration.
  9208. * @param callback a success call back that will be called when iterating stops.
  9209. * @param breakFunction a break condition (optional)
  9210. * @param timeout timeout settings for the setTimeout function. default - 0.
  9211. * @constructor
  9212. */
  9213. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9214. if (timeout === void 0) { timeout = 0; }
  9215. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9216. if (breakFunction && breakFunction())
  9217. loop.breakLoop();
  9218. else {
  9219. setTimeout(function () {
  9220. for (var i = 0; i < syncedIterations; ++i) {
  9221. var iteration = (loop.index * syncedIterations) + i;
  9222. if (iteration >= iterations)
  9223. break;
  9224. fn(iteration);
  9225. if (breakFunction && breakFunction()) {
  9226. loop.breakLoop();
  9227. break;
  9228. }
  9229. }
  9230. loop.executeNext();
  9231. }, timeout);
  9232. }
  9233. }, callback);
  9234. };
  9235. return AsyncLoop;
  9236. }());
  9237. BABYLON.AsyncLoop = AsyncLoop;
  9238. })(BABYLON || (BABYLON = {}));
  9239. //# sourceMappingURL=babylon.tools.js.map
  9240. var BABYLON;
  9241. (function (BABYLON) {
  9242. var PromiseStates;
  9243. (function (PromiseStates) {
  9244. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9245. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9246. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9247. })(PromiseStates || (PromiseStates = {}));
  9248. var FulFillmentAgregator = /** @class */ (function () {
  9249. function FulFillmentAgregator() {
  9250. this.count = 0;
  9251. this.target = 0;
  9252. this.results = [];
  9253. }
  9254. return FulFillmentAgregator;
  9255. }());
  9256. var InternalPromise = /** @class */ (function () {
  9257. function InternalPromise(resolver) {
  9258. var _this = this;
  9259. this._state = PromiseStates.Pending;
  9260. this._children = new Array();
  9261. this._rejectWasConsumed = false;
  9262. if (!resolver) {
  9263. return;
  9264. }
  9265. try {
  9266. resolver(function (value) {
  9267. _this._resolve(value);
  9268. }, function (reason) {
  9269. _this._reject(reason);
  9270. });
  9271. }
  9272. catch (e) {
  9273. this._reject(e);
  9274. }
  9275. }
  9276. Object.defineProperty(InternalPromise.prototype, "state", {
  9277. get: function () {
  9278. return this._state;
  9279. },
  9280. enumerable: true,
  9281. configurable: true
  9282. });
  9283. Object.defineProperty(InternalPromise.prototype, "isFulfilled", {
  9284. get: function () {
  9285. return this._state === PromiseStates.Fulfilled;
  9286. },
  9287. enumerable: true,
  9288. configurable: true
  9289. });
  9290. Object.defineProperty(InternalPromise.prototype, "isRejected", {
  9291. get: function () {
  9292. return this._state === PromiseStates.Rejected;
  9293. },
  9294. enumerable: true,
  9295. configurable: true
  9296. });
  9297. Object.defineProperty(InternalPromise.prototype, "isPending", {
  9298. get: function () {
  9299. return this._state === PromiseStates.Pending;
  9300. },
  9301. enumerable: true,
  9302. configurable: true
  9303. });
  9304. InternalPromise.prototype.value = function () {
  9305. if (!this.isFulfilled) {
  9306. throw new Error("Promise is not fulfilled");
  9307. }
  9308. return this._result;
  9309. };
  9310. InternalPromise.prototype.reason = function () {
  9311. if (!this.isRejected) {
  9312. throw new Error("Promise is not rejected");
  9313. }
  9314. return this._reason;
  9315. };
  9316. InternalPromise.prototype.catch = function (onRejected) {
  9317. return this.then(undefined, onRejected);
  9318. };
  9319. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9320. var newPromise = new InternalPromise();
  9321. newPromise._onFulfilled = onFulfilled;
  9322. newPromise._onRejected = onRejected;
  9323. // Composition
  9324. this._children.push(newPromise);
  9325. if (this._state !== PromiseStates.Pending) {
  9326. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  9327. var returnedValue = newPromise._resolve(this._result);
  9328. if (returnedValue !== undefined && returnedValue !== null) {
  9329. if (returnedValue._state !== undefined) {
  9330. var returnedPromise = returnedValue;
  9331. newPromise._children.push(returnedPromise);
  9332. newPromise = returnedPromise;
  9333. }
  9334. else {
  9335. newPromise._result = returnedValue;
  9336. }
  9337. }
  9338. }
  9339. else {
  9340. newPromise._reject(this._reason);
  9341. }
  9342. }
  9343. return newPromise;
  9344. };
  9345. InternalPromise.prototype._moveChildren = function (children) {
  9346. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9347. if (this.isFulfilled) {
  9348. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9349. var child = _b[_i];
  9350. child._resolve(this._result);
  9351. }
  9352. }
  9353. else if (this.isRejected) {
  9354. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9355. var child = _d[_c];
  9356. child._reject(this._reason);
  9357. }
  9358. }
  9359. var _a;
  9360. };
  9361. InternalPromise.prototype._resolve = function (value) {
  9362. try {
  9363. this._state = PromiseStates.Fulfilled;
  9364. this._result = value;
  9365. var returnedValue = null;
  9366. if (this._onFulfilled) {
  9367. returnedValue = this._onFulfilled(value);
  9368. }
  9369. if (returnedValue !== undefined && returnedValue !== null) {
  9370. if (returnedValue._state !== undefined) {
  9371. // Transmit children
  9372. var returnedPromise = returnedValue;
  9373. returnedPromise._moveChildren(this._children);
  9374. }
  9375. else {
  9376. value = returnedValue;
  9377. }
  9378. }
  9379. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9380. var child = _a[_i];
  9381. child._resolve(value);
  9382. }
  9383. return returnedValue;
  9384. }
  9385. catch (e) {
  9386. this._reject(e);
  9387. }
  9388. return null;
  9389. };
  9390. InternalPromise.prototype._reject = function (reason) {
  9391. this._state = PromiseStates.Rejected;
  9392. this._reason = reason;
  9393. if (this._onRejected) {
  9394. this._onRejected(reason);
  9395. this._rejectWasConsumed = true;
  9396. }
  9397. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9398. var child = _a[_i];
  9399. if (this._rejectWasConsumed) {
  9400. child._resolve(null);
  9401. }
  9402. else {
  9403. child._reject(reason);
  9404. }
  9405. }
  9406. };
  9407. InternalPromise.resolve = function (value) {
  9408. var newPromise = new InternalPromise();
  9409. newPromise._resolve(value);
  9410. return newPromise;
  9411. };
  9412. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9413. promise.then(function (value) {
  9414. agregator.results[index] = value;
  9415. agregator.count++;
  9416. if (agregator.count === agregator.target) {
  9417. agregator.rootPromise._resolve(agregator.results);
  9418. }
  9419. return null;
  9420. }, function (reason) {
  9421. if (!agregator.rootPromise.isRejected) {
  9422. agregator.rootPromise._reject(reason);
  9423. }
  9424. });
  9425. };
  9426. InternalPromise.all = function (promises) {
  9427. var newPromise = new InternalPromise();
  9428. var agregator = new FulFillmentAgregator();
  9429. agregator.target = promises.length;
  9430. agregator.rootPromise = newPromise;
  9431. if (promises.length) {
  9432. for (var index = 0; index < promises.length; index++) {
  9433. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9434. }
  9435. }
  9436. else {
  9437. newPromise._resolve([]);
  9438. }
  9439. return newPromise;
  9440. };
  9441. return InternalPromise;
  9442. }());
  9443. /**
  9444. * Helper class that provides a small promise polyfill
  9445. */
  9446. var PromisePolyfill = /** @class */ (function () {
  9447. function PromisePolyfill() {
  9448. }
  9449. /**
  9450. * Static function used to check if the polyfill is required
  9451. * If this is the case then the function will inject the polyfill to window.Promise
  9452. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9453. */
  9454. PromisePolyfill.Apply = function (force) {
  9455. if (force === void 0) { force = false; }
  9456. if (force || typeof Promise === 'undefined') {
  9457. var root = window;
  9458. root.Promise = InternalPromise;
  9459. }
  9460. };
  9461. return PromisePolyfill;
  9462. }());
  9463. BABYLON.PromisePolyfill = PromisePolyfill;
  9464. })(BABYLON || (BABYLON = {}));
  9465. //# sourceMappingURL=babylon.promise.js.map
  9466. var BABYLON;
  9467. (function (BABYLON) {
  9468. var _AlphaState = /** @class */ (function () {
  9469. /**
  9470. * Initializes the state.
  9471. */
  9472. function _AlphaState() {
  9473. this._isAlphaBlendDirty = false;
  9474. this._isBlendFunctionParametersDirty = false;
  9475. this._isBlendEquationParametersDirty = false;
  9476. this._isBlendConstantsDirty = false;
  9477. this._alphaBlend = false;
  9478. this._blendFunctionParameters = new Array(4);
  9479. this._blendEquationParameters = new Array(2);
  9480. this._blendConstants = new Array(4);
  9481. this.reset();
  9482. }
  9483. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9484. get: function () {
  9485. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9486. },
  9487. enumerable: true,
  9488. configurable: true
  9489. });
  9490. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9491. get: function () {
  9492. return this._alphaBlend;
  9493. },
  9494. set: function (value) {
  9495. if (this._alphaBlend === value) {
  9496. return;
  9497. }
  9498. this._alphaBlend = value;
  9499. this._isAlphaBlendDirty = true;
  9500. },
  9501. enumerable: true,
  9502. configurable: true
  9503. });
  9504. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9505. if (this._blendConstants[0] === r &&
  9506. this._blendConstants[1] === g &&
  9507. this._blendConstants[2] === b &&
  9508. this._blendConstants[3] === a) {
  9509. return;
  9510. }
  9511. this._blendConstants[0] = r;
  9512. this._blendConstants[1] = g;
  9513. this._blendConstants[2] = b;
  9514. this._blendConstants[3] = a;
  9515. this._isBlendConstantsDirty = true;
  9516. };
  9517. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9518. if (this._blendFunctionParameters[0] === value0 &&
  9519. this._blendFunctionParameters[1] === value1 &&
  9520. this._blendFunctionParameters[2] === value2 &&
  9521. this._blendFunctionParameters[3] === value3) {
  9522. return;
  9523. }
  9524. this._blendFunctionParameters[0] = value0;
  9525. this._blendFunctionParameters[1] = value1;
  9526. this._blendFunctionParameters[2] = value2;
  9527. this._blendFunctionParameters[3] = value3;
  9528. this._isBlendFunctionParametersDirty = true;
  9529. };
  9530. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9531. if (this._blendEquationParameters[0] === rgb &&
  9532. this._blendEquationParameters[1] === alpha) {
  9533. return;
  9534. }
  9535. this._blendEquationParameters[0] = rgb;
  9536. this._blendEquationParameters[1] = alpha;
  9537. this._isBlendEquationParametersDirty = true;
  9538. };
  9539. _AlphaState.prototype.reset = function () {
  9540. this._alphaBlend = false;
  9541. this._blendFunctionParameters[0] = null;
  9542. this._blendFunctionParameters[1] = null;
  9543. this._blendFunctionParameters[2] = null;
  9544. this._blendFunctionParameters[3] = null;
  9545. this._blendEquationParameters[0] = null;
  9546. this._blendEquationParameters[1] = null;
  9547. this._blendConstants[0] = null;
  9548. this._blendConstants[1] = null;
  9549. this._blendConstants[2] = null;
  9550. this._blendConstants[3] = null;
  9551. this._isAlphaBlendDirty = true;
  9552. this._isBlendFunctionParametersDirty = false;
  9553. this._isBlendEquationParametersDirty = false;
  9554. this._isBlendConstantsDirty = false;
  9555. };
  9556. _AlphaState.prototype.apply = function (gl) {
  9557. if (!this.isDirty) {
  9558. return;
  9559. }
  9560. // Alpha blend
  9561. if (this._isAlphaBlendDirty) {
  9562. if (this._alphaBlend) {
  9563. gl.enable(gl.BLEND);
  9564. }
  9565. else {
  9566. gl.disable(gl.BLEND);
  9567. }
  9568. this._isAlphaBlendDirty = false;
  9569. }
  9570. // Alpha function
  9571. if (this._isBlendFunctionParametersDirty) {
  9572. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9573. this._isBlendFunctionParametersDirty = false;
  9574. }
  9575. // Alpha equation
  9576. if (this._isBlendEquationParametersDirty) {
  9577. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9578. this._isBlendEquationParametersDirty = false;
  9579. }
  9580. // Constants
  9581. if (this._isBlendConstantsDirty) {
  9582. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9583. this._isBlendConstantsDirty = false;
  9584. }
  9585. };
  9586. return _AlphaState;
  9587. }());
  9588. BABYLON._AlphaState = _AlphaState;
  9589. })(BABYLON || (BABYLON = {}));
  9590. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9591. var BABYLON;
  9592. (function (BABYLON) {
  9593. var _DepthCullingState = /** @class */ (function () {
  9594. /**
  9595. * Initializes the state.
  9596. */
  9597. function _DepthCullingState() {
  9598. this._isDepthTestDirty = false;
  9599. this._isDepthMaskDirty = false;
  9600. this._isDepthFuncDirty = false;
  9601. this._isCullFaceDirty = false;
  9602. this._isCullDirty = false;
  9603. this._isZOffsetDirty = false;
  9604. this._isFrontFaceDirty = false;
  9605. this.reset();
  9606. }
  9607. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9608. get: function () {
  9609. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9610. },
  9611. enumerable: true,
  9612. configurable: true
  9613. });
  9614. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9615. get: function () {
  9616. return this._zOffset;
  9617. },
  9618. set: function (value) {
  9619. if (this._zOffset === value) {
  9620. return;
  9621. }
  9622. this._zOffset = value;
  9623. this._isZOffsetDirty = true;
  9624. },
  9625. enumerable: true,
  9626. configurable: true
  9627. });
  9628. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9629. get: function () {
  9630. return this._cullFace;
  9631. },
  9632. set: function (value) {
  9633. if (this._cullFace === value) {
  9634. return;
  9635. }
  9636. this._cullFace = value;
  9637. this._isCullFaceDirty = true;
  9638. },
  9639. enumerable: true,
  9640. configurable: true
  9641. });
  9642. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9643. get: function () {
  9644. return this._cull;
  9645. },
  9646. set: function (value) {
  9647. if (this._cull === value) {
  9648. return;
  9649. }
  9650. this._cull = value;
  9651. this._isCullDirty = true;
  9652. },
  9653. enumerable: true,
  9654. configurable: true
  9655. });
  9656. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9657. get: function () {
  9658. return this._depthFunc;
  9659. },
  9660. set: function (value) {
  9661. if (this._depthFunc === value) {
  9662. return;
  9663. }
  9664. this._depthFunc = value;
  9665. this._isDepthFuncDirty = true;
  9666. },
  9667. enumerable: true,
  9668. configurable: true
  9669. });
  9670. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9671. get: function () {
  9672. return this._depthMask;
  9673. },
  9674. set: function (value) {
  9675. if (this._depthMask === value) {
  9676. return;
  9677. }
  9678. this._depthMask = value;
  9679. this._isDepthMaskDirty = true;
  9680. },
  9681. enumerable: true,
  9682. configurable: true
  9683. });
  9684. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9685. get: function () {
  9686. return this._depthTest;
  9687. },
  9688. set: function (value) {
  9689. if (this._depthTest === value) {
  9690. return;
  9691. }
  9692. this._depthTest = value;
  9693. this._isDepthTestDirty = true;
  9694. },
  9695. enumerable: true,
  9696. configurable: true
  9697. });
  9698. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9699. get: function () {
  9700. return this._frontFace;
  9701. },
  9702. set: function (value) {
  9703. if (this._frontFace === value) {
  9704. return;
  9705. }
  9706. this._frontFace = value;
  9707. this._isFrontFaceDirty = true;
  9708. },
  9709. enumerable: true,
  9710. configurable: true
  9711. });
  9712. _DepthCullingState.prototype.reset = function () {
  9713. this._depthMask = true;
  9714. this._depthTest = true;
  9715. this._depthFunc = null;
  9716. this._cullFace = null;
  9717. this._cull = null;
  9718. this._zOffset = 0;
  9719. this._frontFace = null;
  9720. this._isDepthTestDirty = true;
  9721. this._isDepthMaskDirty = true;
  9722. this._isDepthFuncDirty = false;
  9723. this._isCullFaceDirty = false;
  9724. this._isCullDirty = false;
  9725. this._isZOffsetDirty = false;
  9726. this._isFrontFaceDirty = false;
  9727. };
  9728. _DepthCullingState.prototype.apply = function (gl) {
  9729. if (!this.isDirty) {
  9730. return;
  9731. }
  9732. // Cull
  9733. if (this._isCullDirty) {
  9734. if (this.cull) {
  9735. gl.enable(gl.CULL_FACE);
  9736. }
  9737. else {
  9738. gl.disable(gl.CULL_FACE);
  9739. }
  9740. this._isCullDirty = false;
  9741. }
  9742. // Cull face
  9743. if (this._isCullFaceDirty) {
  9744. gl.cullFace(this.cullFace);
  9745. this._isCullFaceDirty = false;
  9746. }
  9747. // Depth mask
  9748. if (this._isDepthMaskDirty) {
  9749. gl.depthMask(this.depthMask);
  9750. this._isDepthMaskDirty = false;
  9751. }
  9752. // Depth test
  9753. if (this._isDepthTestDirty) {
  9754. if (this.depthTest) {
  9755. gl.enable(gl.DEPTH_TEST);
  9756. }
  9757. else {
  9758. gl.disable(gl.DEPTH_TEST);
  9759. }
  9760. this._isDepthTestDirty = false;
  9761. }
  9762. // Depth func
  9763. if (this._isDepthFuncDirty) {
  9764. gl.depthFunc(this.depthFunc);
  9765. this._isDepthFuncDirty = false;
  9766. }
  9767. // zOffset
  9768. if (this._isZOffsetDirty) {
  9769. if (this.zOffset) {
  9770. gl.enable(gl.POLYGON_OFFSET_FILL);
  9771. gl.polygonOffset(this.zOffset, 0);
  9772. }
  9773. else {
  9774. gl.disable(gl.POLYGON_OFFSET_FILL);
  9775. }
  9776. this._isZOffsetDirty = false;
  9777. }
  9778. // Front face
  9779. if (this._isFrontFaceDirty) {
  9780. gl.frontFace(this.frontFace);
  9781. this._isFrontFaceDirty = false;
  9782. }
  9783. };
  9784. return _DepthCullingState;
  9785. }());
  9786. BABYLON._DepthCullingState = _DepthCullingState;
  9787. })(BABYLON || (BABYLON = {}));
  9788. //# sourceMappingURL=babylon.depthCullingState.js.map
  9789. var BABYLON;
  9790. (function (BABYLON) {
  9791. var _StencilState = /** @class */ (function () {
  9792. function _StencilState() {
  9793. this._isStencilTestDirty = false;
  9794. this._isStencilMaskDirty = false;
  9795. this._isStencilFuncDirty = false;
  9796. this._isStencilOpDirty = false;
  9797. this.reset();
  9798. }
  9799. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9800. get: function () {
  9801. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9802. },
  9803. enumerable: true,
  9804. configurable: true
  9805. });
  9806. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9807. get: function () {
  9808. return this._stencilFunc;
  9809. },
  9810. set: function (value) {
  9811. if (this._stencilFunc === value) {
  9812. return;
  9813. }
  9814. this._stencilFunc = value;
  9815. this._isStencilFuncDirty = true;
  9816. },
  9817. enumerable: true,
  9818. configurable: true
  9819. });
  9820. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9821. get: function () {
  9822. return this._stencilFuncRef;
  9823. },
  9824. set: function (value) {
  9825. if (this._stencilFuncRef === value) {
  9826. return;
  9827. }
  9828. this._stencilFuncRef = value;
  9829. this._isStencilFuncDirty = true;
  9830. },
  9831. enumerable: true,
  9832. configurable: true
  9833. });
  9834. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9835. get: function () {
  9836. return this._stencilFuncMask;
  9837. },
  9838. set: function (value) {
  9839. if (this._stencilFuncMask === value) {
  9840. return;
  9841. }
  9842. this._stencilFuncMask = value;
  9843. this._isStencilFuncDirty = true;
  9844. },
  9845. enumerable: true,
  9846. configurable: true
  9847. });
  9848. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9849. get: function () {
  9850. return this._stencilOpStencilFail;
  9851. },
  9852. set: function (value) {
  9853. if (this._stencilOpStencilFail === value) {
  9854. return;
  9855. }
  9856. this._stencilOpStencilFail = value;
  9857. this._isStencilOpDirty = true;
  9858. },
  9859. enumerable: true,
  9860. configurable: true
  9861. });
  9862. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9863. get: function () {
  9864. return this._stencilOpDepthFail;
  9865. },
  9866. set: function (value) {
  9867. if (this._stencilOpDepthFail === value) {
  9868. return;
  9869. }
  9870. this._stencilOpDepthFail = value;
  9871. this._isStencilOpDirty = true;
  9872. },
  9873. enumerable: true,
  9874. configurable: true
  9875. });
  9876. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9877. get: function () {
  9878. return this._stencilOpStencilDepthPass;
  9879. },
  9880. set: function (value) {
  9881. if (this._stencilOpStencilDepthPass === value) {
  9882. return;
  9883. }
  9884. this._stencilOpStencilDepthPass = value;
  9885. this._isStencilOpDirty = true;
  9886. },
  9887. enumerable: true,
  9888. configurable: true
  9889. });
  9890. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9891. get: function () {
  9892. return this._stencilMask;
  9893. },
  9894. set: function (value) {
  9895. if (this._stencilMask === value) {
  9896. return;
  9897. }
  9898. this._stencilMask = value;
  9899. this._isStencilMaskDirty = true;
  9900. },
  9901. enumerable: true,
  9902. configurable: true
  9903. });
  9904. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9905. get: function () {
  9906. return this._stencilTest;
  9907. },
  9908. set: function (value) {
  9909. if (this._stencilTest === value) {
  9910. return;
  9911. }
  9912. this._stencilTest = value;
  9913. this._isStencilTestDirty = true;
  9914. },
  9915. enumerable: true,
  9916. configurable: true
  9917. });
  9918. _StencilState.prototype.reset = function () {
  9919. this._stencilTest = false;
  9920. this._stencilMask = 0xFF;
  9921. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9922. this._stencilFuncRef = 1;
  9923. this._stencilFuncMask = 0xFF;
  9924. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9925. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9926. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9927. this._isStencilTestDirty = true;
  9928. this._isStencilMaskDirty = true;
  9929. this._isStencilFuncDirty = true;
  9930. this._isStencilOpDirty = true;
  9931. };
  9932. _StencilState.prototype.apply = function (gl) {
  9933. if (!this.isDirty) {
  9934. return;
  9935. }
  9936. // Stencil test
  9937. if (this._isStencilTestDirty) {
  9938. if (this.stencilTest) {
  9939. gl.enable(gl.STENCIL_TEST);
  9940. }
  9941. else {
  9942. gl.disable(gl.STENCIL_TEST);
  9943. }
  9944. this._isStencilTestDirty = false;
  9945. }
  9946. // Stencil mask
  9947. if (this._isStencilMaskDirty) {
  9948. gl.stencilMask(this.stencilMask);
  9949. this._isStencilMaskDirty = false;
  9950. }
  9951. // Stencil func
  9952. if (this._isStencilFuncDirty) {
  9953. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9954. this._isStencilFuncDirty = false;
  9955. }
  9956. // Stencil op
  9957. if (this._isStencilOpDirty) {
  9958. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9959. this._isStencilOpDirty = false;
  9960. }
  9961. };
  9962. return _StencilState;
  9963. }());
  9964. BABYLON._StencilState = _StencilState;
  9965. })(BABYLON || (BABYLON = {}));
  9966. //# sourceMappingURL=babylon.stencilState.js.map
  9967. var BABYLON;
  9968. (function (BABYLON) {
  9969. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9970. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9971. };
  9972. var compileRawShader = function (gl, source, type) {
  9973. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9974. gl.shaderSource(shader, source);
  9975. gl.compileShader(shader);
  9976. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9977. var log = gl.getShaderInfoLog(shader);
  9978. if (log) {
  9979. throw new Error(log);
  9980. }
  9981. }
  9982. if (!shader) {
  9983. throw new Error("Something went wrong while compile the shader.");
  9984. }
  9985. return shader;
  9986. };
  9987. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9988. var magFilter = gl.NEAREST;
  9989. var minFilter = gl.NEAREST;
  9990. switch (samplingMode) {
  9991. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9992. magFilter = gl.LINEAR;
  9993. if (generateMipMaps) {
  9994. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9995. }
  9996. else {
  9997. minFilter = gl.LINEAR;
  9998. }
  9999. break;
  10000. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10001. magFilter = gl.LINEAR;
  10002. if (generateMipMaps) {
  10003. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10004. }
  10005. else {
  10006. minFilter = gl.LINEAR;
  10007. }
  10008. break;
  10009. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10010. magFilter = gl.NEAREST;
  10011. if (generateMipMaps) {
  10012. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10013. }
  10014. else {
  10015. minFilter = gl.NEAREST;
  10016. }
  10017. break;
  10018. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10019. magFilter = gl.NEAREST;
  10020. if (generateMipMaps) {
  10021. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10022. }
  10023. else {
  10024. minFilter = gl.NEAREST;
  10025. }
  10026. break;
  10027. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10028. magFilter = gl.NEAREST;
  10029. if (generateMipMaps) {
  10030. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10031. }
  10032. else {
  10033. minFilter = gl.LINEAR;
  10034. }
  10035. break;
  10036. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10037. magFilter = gl.NEAREST;
  10038. if (generateMipMaps) {
  10039. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10040. }
  10041. else {
  10042. minFilter = gl.LINEAR;
  10043. }
  10044. break;
  10045. case BABYLON.Texture.NEAREST_LINEAR:
  10046. magFilter = gl.NEAREST;
  10047. minFilter = gl.LINEAR;
  10048. break;
  10049. case BABYLON.Texture.NEAREST_NEAREST:
  10050. magFilter = gl.NEAREST;
  10051. minFilter = gl.NEAREST;
  10052. break;
  10053. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10054. magFilter = gl.LINEAR;
  10055. if (generateMipMaps) {
  10056. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10057. }
  10058. else {
  10059. minFilter = gl.NEAREST;
  10060. }
  10061. break;
  10062. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10063. magFilter = gl.LINEAR;
  10064. if (generateMipMaps) {
  10065. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10066. }
  10067. else {
  10068. minFilter = gl.NEAREST;
  10069. }
  10070. break;
  10071. case BABYLON.Texture.LINEAR_LINEAR:
  10072. magFilter = gl.LINEAR;
  10073. minFilter = gl.LINEAR;
  10074. break;
  10075. case BABYLON.Texture.LINEAR_NEAREST:
  10076. magFilter = gl.LINEAR;
  10077. minFilter = gl.NEAREST;
  10078. break;
  10079. }
  10080. return {
  10081. min: minFilter,
  10082. mag: magFilter
  10083. };
  10084. };
  10085. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10086. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10087. var img;
  10088. var onload = function () {
  10089. loadedImages[index] = img;
  10090. loadedImages._internalCount++;
  10091. if (scene) {
  10092. scene._removePendingData(img);
  10093. }
  10094. if (loadedImages._internalCount === 6) {
  10095. onfinish(loadedImages);
  10096. }
  10097. };
  10098. var onerror = function (message, exception) {
  10099. if (scene) {
  10100. scene._removePendingData(img);
  10101. }
  10102. if (onErrorCallBack) {
  10103. onErrorCallBack(message, exception);
  10104. }
  10105. };
  10106. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10107. if (scene) {
  10108. scene._addPendingData(img);
  10109. }
  10110. };
  10111. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10112. if (onError === void 0) { onError = null; }
  10113. var loadedImages = [];
  10114. loadedImages._internalCount = 0;
  10115. for (var index = 0; index < 6; index++) {
  10116. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10117. }
  10118. };
  10119. var BufferPointer = /** @class */ (function () {
  10120. function BufferPointer() {
  10121. }
  10122. return BufferPointer;
  10123. }());
  10124. var InstancingAttributeInfo = /** @class */ (function () {
  10125. function InstancingAttributeInfo() {
  10126. }
  10127. return InstancingAttributeInfo;
  10128. }());
  10129. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10130. /**
  10131. * Define options used to create a render target texture
  10132. */
  10133. var RenderTargetCreationOptions = /** @class */ (function () {
  10134. function RenderTargetCreationOptions() {
  10135. }
  10136. return RenderTargetCreationOptions;
  10137. }());
  10138. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10139. /**
  10140. * Regroup several parameters relative to the browser in use
  10141. */
  10142. var EngineCapabilities = /** @class */ (function () {
  10143. function EngineCapabilities() {
  10144. }
  10145. return EngineCapabilities;
  10146. }());
  10147. BABYLON.EngineCapabilities = EngineCapabilities;
  10148. /**
  10149. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10150. */
  10151. var Engine = /** @class */ (function () {
  10152. /**
  10153. * @constructor
  10154. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10155. * @param antialias defines enable antialiasing (default: false)
  10156. * @param options defines further options to be sent to the getContext() function
  10157. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10158. */
  10159. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10160. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10161. var _this = this;
  10162. // Public members
  10163. this.forcePOTTextures = false;
  10164. this.isFullscreen = false;
  10165. this.isPointerLock = false;
  10166. this.cullBackFaces = true;
  10167. this.renderEvenInBackground = true;
  10168. this.preventCacheWipeBetweenFrames = false;
  10169. // To enable/disable IDB support and avoid XHR on .manifest
  10170. this.enableOfflineSupport = false;
  10171. this.scenes = new Array();
  10172. this.postProcesses = new Array();
  10173. // Observables
  10174. /**
  10175. * Observable event triggered each time the rendering canvas is resized
  10176. */
  10177. this.onResizeObservable = new BABYLON.Observable();
  10178. /**
  10179. * Observable event triggered each time the canvas loses focus
  10180. */
  10181. this.onCanvasBlurObservable = new BABYLON.Observable();
  10182. /**
  10183. * Observable event triggered each time the canvas gains focus
  10184. */
  10185. this.onCanvasFocusObservable = new BABYLON.Observable();
  10186. /**
  10187. * Observable event triggered each time the canvas receives pointerout event
  10188. */
  10189. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10190. /**
  10191. * Observable event triggered before each texture is initialized
  10192. */
  10193. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10194. //WebVR
  10195. this._vrDisplay = undefined;
  10196. this._vrSupported = false;
  10197. this._vrExclusivePointerMode = false;
  10198. // Uniform buffers list
  10199. this.disableUniformBuffers = false;
  10200. this._uniformBuffers = new Array();
  10201. // Observables
  10202. /**
  10203. * Observable raised when the engine begins a new frame
  10204. */
  10205. this.onBeginFrameObservable = new BABYLON.Observable();
  10206. /**
  10207. * Observable raised when the engine ends the current frame
  10208. */
  10209. this.onEndFrameObservable = new BABYLON.Observable();
  10210. /**
  10211. * Observable raised when the engine is about to compile a shader
  10212. */
  10213. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10214. /**
  10215. * Observable raised when the engine has jsut compiled a shader
  10216. */
  10217. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10218. this._windowIsBackground = false;
  10219. this._webGLVersion = 1.0;
  10220. this._badOS = false;
  10221. this._badDesktopOS = false;
  10222. /**
  10223. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10224. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10225. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10226. */
  10227. this.disableTextureBindingOptimization = false;
  10228. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10229. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10230. this.onVRRequestPresentStart = new BABYLON.Observable();
  10231. this._colorWrite = true;
  10232. this._drawCalls = new BABYLON.PerfCounter();
  10233. this._textureCollisions = new BABYLON.PerfCounter();
  10234. this._renderingQueueLaunched = false;
  10235. this._activeRenderLoops = new Array();
  10236. // Deterministic lockstepMaxSteps
  10237. this._deterministicLockstep = false;
  10238. this._lockstepMaxSteps = 4;
  10239. // Lost context
  10240. this.onContextLostObservable = new BABYLON.Observable();
  10241. this.onContextRestoredObservable = new BABYLON.Observable();
  10242. this._contextWasLost = false;
  10243. this._doNotHandleContextLost = false;
  10244. // FPS
  10245. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10246. this._fps = 60;
  10247. this._deltaTime = 0;
  10248. /**
  10249. * Turn this value on if you want to pause FPS computation when in background
  10250. */
  10251. this.disablePerformanceMonitorInBackground = false;
  10252. // States
  10253. this._depthCullingState = new BABYLON._DepthCullingState();
  10254. this._stencilState = new BABYLON._StencilState();
  10255. this._alphaState = new BABYLON._AlphaState();
  10256. this._alphaMode = Engine.ALPHA_DISABLE;
  10257. // Cache
  10258. this._internalTexturesCache = new Array();
  10259. this._activeChannel = 0;
  10260. this._currentTextureChannel = -1;
  10261. this._boundTexturesCache = {};
  10262. this._compiledEffects = {};
  10263. this._vertexAttribArraysEnabled = [];
  10264. this._uintIndicesCurrentlySet = false;
  10265. this._currentBoundBuffer = new Array();
  10266. this._currentBufferPointers = new Array();
  10267. this._currentInstanceLocations = new Array();
  10268. this._currentInstanceBuffers = new Array();
  10269. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10270. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10271. this._vaoRecordInProgress = false;
  10272. this._mustWipeVertexAttributes = false;
  10273. this._nextFreeTextureSlots = new Array();
  10274. this._maxSimultaneousTextures = 0;
  10275. this._activeRequests = new Array();
  10276. // Hardware supported Compressed Textures
  10277. this._texturesSupported = new Array();
  10278. this._onVRFullScreenTriggered = function () {
  10279. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10280. //get the old size before we change
  10281. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10282. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10283. //get the width and height, change the render size
  10284. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10285. _this.setHardwareScalingLevel(1);
  10286. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10287. }
  10288. else {
  10289. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10290. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10291. }
  10292. };
  10293. this._boundUniforms = {};
  10294. // Register promises
  10295. BABYLON.PromisePolyfill.Apply();
  10296. var canvas = null;
  10297. Engine.Instances.push(this);
  10298. if (!canvasOrContext) {
  10299. return;
  10300. }
  10301. options = options || {};
  10302. if (canvasOrContext.getContext) {
  10303. canvas = canvasOrContext;
  10304. this._renderingCanvas = canvas;
  10305. if (antialias != null) {
  10306. options.antialias = antialias;
  10307. }
  10308. if (options.deterministicLockstep === undefined) {
  10309. options.deterministicLockstep = false;
  10310. }
  10311. if (options.lockstepMaxSteps === undefined) {
  10312. options.lockstepMaxSteps = 4;
  10313. }
  10314. if (options.preserveDrawingBuffer === undefined) {
  10315. options.preserveDrawingBuffer = false;
  10316. }
  10317. if (options.audioEngine === undefined) {
  10318. options.audioEngine = true;
  10319. }
  10320. if (options.stencil === undefined) {
  10321. options.stencil = true;
  10322. }
  10323. this._deterministicLockstep = options.deterministicLockstep;
  10324. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10325. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10326. // Exceptions
  10327. if (navigator && navigator.userAgent) {
  10328. var ua = navigator.userAgent;
  10329. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10330. var exception = _a[_i];
  10331. var key = exception.key;
  10332. var targets = exception.targets;
  10333. if (ua.indexOf(key) > -1) {
  10334. if (exception.capture && exception.captureConstraint) {
  10335. var capture = exception.capture;
  10336. var constraint = exception.captureConstraint;
  10337. var regex = new RegExp(capture);
  10338. var matches = regex.exec(ua);
  10339. if (matches && matches.length > 0) {
  10340. var capturedValue = parseInt(matches[matches.length - 1]);
  10341. if (capturedValue >= constraint) {
  10342. continue;
  10343. }
  10344. }
  10345. }
  10346. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10347. var target = targets_1[_b];
  10348. switch (target) {
  10349. case "uniformBuffer":
  10350. this.disableUniformBuffers = true;
  10351. break;
  10352. case "textureBindingOptimization":
  10353. this.disableTextureBindingOptimization = true;
  10354. break;
  10355. }
  10356. }
  10357. break;
  10358. }
  10359. }
  10360. }
  10361. // GL
  10362. if (!options.disableWebGL2Support) {
  10363. try {
  10364. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10365. if (this._gl) {
  10366. this._webGLVersion = 2.0;
  10367. }
  10368. }
  10369. catch (e) {
  10370. // Do nothing
  10371. }
  10372. }
  10373. if (!this._gl) {
  10374. if (!canvas) {
  10375. throw new Error("The provided canvas is null or undefined.");
  10376. }
  10377. try {
  10378. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10379. }
  10380. catch (e) {
  10381. throw new Error("WebGL not supported");
  10382. }
  10383. }
  10384. if (!this._gl) {
  10385. throw new Error("WebGL not supported");
  10386. }
  10387. this._onCanvasFocus = function () {
  10388. _this.onCanvasFocusObservable.notifyObservers(_this);
  10389. };
  10390. this._onCanvasBlur = function () {
  10391. _this.onCanvasBlurObservable.notifyObservers(_this);
  10392. };
  10393. canvas.addEventListener("focus", this._onCanvasFocus);
  10394. canvas.addEventListener("blur", this._onCanvasBlur);
  10395. this._onBlur = function () {
  10396. if (_this.disablePerformanceMonitorInBackground) {
  10397. _this._performanceMonitor.disable();
  10398. }
  10399. _this._windowIsBackground = true;
  10400. };
  10401. this._onFocus = function () {
  10402. if (_this.disablePerformanceMonitorInBackground) {
  10403. _this._performanceMonitor.enable();
  10404. }
  10405. _this._windowIsBackground = false;
  10406. };
  10407. this._onCanvasPointerOut = function () {
  10408. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10409. };
  10410. window.addEventListener("blur", this._onBlur);
  10411. window.addEventListener("focus", this._onFocus);
  10412. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10413. // Context lost
  10414. if (!this._doNotHandleContextLost) {
  10415. this._onContextLost = function (evt) {
  10416. evt.preventDefault();
  10417. _this._contextWasLost = true;
  10418. BABYLON.Tools.Warn("WebGL context lost.");
  10419. _this.onContextLostObservable.notifyObservers(_this);
  10420. };
  10421. this._onContextRestored = function (evt) {
  10422. // Adding a timeout to avoid race condition at browser level
  10423. setTimeout(function () {
  10424. // Rebuild gl context
  10425. _this._initGLContext();
  10426. // Rebuild effects
  10427. _this._rebuildEffects();
  10428. // Rebuild textures
  10429. _this._rebuildInternalTextures();
  10430. // Rebuild buffers
  10431. _this._rebuildBuffers();
  10432. // Cache
  10433. _this.wipeCaches(true);
  10434. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10435. _this.onContextRestoredObservable.notifyObservers(_this);
  10436. _this._contextWasLost = false;
  10437. }, 0);
  10438. };
  10439. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10440. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10441. }
  10442. }
  10443. else {
  10444. this._gl = canvasOrContext;
  10445. this._renderingCanvas = this._gl.canvas;
  10446. if (this._gl.renderbufferStorageMultisample) {
  10447. this._webGLVersion = 2.0;
  10448. }
  10449. options.stencil = this._gl.getContextAttributes().stencil;
  10450. }
  10451. // Viewport
  10452. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10453. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10454. this.resize();
  10455. this._isStencilEnable = options.stencil ? true : false;
  10456. this._initGLContext();
  10457. if (canvas) {
  10458. // Fullscreen
  10459. this._onFullscreenChange = function () {
  10460. if (document.fullscreen !== undefined) {
  10461. _this.isFullscreen = document.fullscreen;
  10462. }
  10463. else if (document.mozFullScreen !== undefined) {
  10464. _this.isFullscreen = document.mozFullScreen;
  10465. }
  10466. else if (document.webkitIsFullScreen !== undefined) {
  10467. _this.isFullscreen = document.webkitIsFullScreen;
  10468. }
  10469. else if (document.msIsFullScreen !== undefined) {
  10470. _this.isFullscreen = document.msIsFullScreen;
  10471. }
  10472. // Pointer lock
  10473. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10474. canvas.requestPointerLock = canvas.requestPointerLock ||
  10475. canvas.msRequestPointerLock ||
  10476. canvas.mozRequestPointerLock ||
  10477. canvas.webkitRequestPointerLock;
  10478. if (canvas.requestPointerLock) {
  10479. canvas.requestPointerLock();
  10480. }
  10481. }
  10482. };
  10483. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10484. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10485. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10486. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10487. // Pointer lock
  10488. this._onPointerLockChange = function () {
  10489. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10490. document.webkitPointerLockElement === canvas ||
  10491. document.msPointerLockElement === canvas ||
  10492. document.pointerLockElement === canvas);
  10493. };
  10494. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10495. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10496. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10497. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10498. this._onVRDisplayPointerRestricted = function () {
  10499. if (canvas) {
  10500. canvas.requestPointerLock();
  10501. }
  10502. };
  10503. this._onVRDisplayPointerUnrestricted = function () {
  10504. document.exitPointerLock();
  10505. };
  10506. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10507. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10508. }
  10509. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10510. Engine.audioEngine = new BABYLON.AudioEngine();
  10511. }
  10512. // Prepare buffer pointers
  10513. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10514. this._currentBufferPointers[i] = new BufferPointer();
  10515. }
  10516. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10517. // Load WebVR Devices
  10518. if (options.autoEnableWebVR) {
  10519. this.initWebVR();
  10520. }
  10521. // Detect if we are running on a faulty buggy OS.
  10522. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10523. // Detect if we are running on a faulty buggy desktop OS.
  10524. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10525. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10526. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10527. }
  10528. Object.defineProperty(Engine, "LastCreatedEngine", {
  10529. get: function () {
  10530. if (Engine.Instances.length === 0) {
  10531. return null;
  10532. }
  10533. return Engine.Instances[Engine.Instances.length - 1];
  10534. },
  10535. enumerable: true,
  10536. configurable: true
  10537. });
  10538. Object.defineProperty(Engine, "LastCreatedScene", {
  10539. get: function () {
  10540. var lastCreatedEngine = Engine.LastCreatedEngine;
  10541. if (!lastCreatedEngine) {
  10542. return null;
  10543. }
  10544. if (lastCreatedEngine.scenes.length === 0) {
  10545. return null;
  10546. }
  10547. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10548. },
  10549. enumerable: true,
  10550. configurable: true
  10551. });
  10552. /**
  10553. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10554. */
  10555. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10556. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10557. var engine = Engine.Instances[engineIndex];
  10558. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10559. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10560. }
  10561. }
  10562. };
  10563. Object.defineProperty(Engine, "NEVER", {
  10564. get: function () {
  10565. return Engine._NEVER;
  10566. },
  10567. enumerable: true,
  10568. configurable: true
  10569. });
  10570. Object.defineProperty(Engine, "ALWAYS", {
  10571. get: function () {
  10572. return Engine._ALWAYS;
  10573. },
  10574. enumerable: true,
  10575. configurable: true
  10576. });
  10577. Object.defineProperty(Engine, "LESS", {
  10578. get: function () {
  10579. return Engine._LESS;
  10580. },
  10581. enumerable: true,
  10582. configurable: true
  10583. });
  10584. Object.defineProperty(Engine, "EQUAL", {
  10585. get: function () {
  10586. return Engine._EQUAL;
  10587. },
  10588. enumerable: true,
  10589. configurable: true
  10590. });
  10591. Object.defineProperty(Engine, "LEQUAL", {
  10592. get: function () {
  10593. return Engine._LEQUAL;
  10594. },
  10595. enumerable: true,
  10596. configurable: true
  10597. });
  10598. Object.defineProperty(Engine, "GREATER", {
  10599. get: function () {
  10600. return Engine._GREATER;
  10601. },
  10602. enumerable: true,
  10603. configurable: true
  10604. });
  10605. Object.defineProperty(Engine, "GEQUAL", {
  10606. get: function () {
  10607. return Engine._GEQUAL;
  10608. },
  10609. enumerable: true,
  10610. configurable: true
  10611. });
  10612. Object.defineProperty(Engine, "NOTEQUAL", {
  10613. get: function () {
  10614. return Engine._NOTEQUAL;
  10615. },
  10616. enumerable: true,
  10617. configurable: true
  10618. });
  10619. Object.defineProperty(Engine, "KEEP", {
  10620. get: function () {
  10621. return Engine._KEEP;
  10622. },
  10623. enumerable: true,
  10624. configurable: true
  10625. });
  10626. Object.defineProperty(Engine, "REPLACE", {
  10627. get: function () {
  10628. return Engine._REPLACE;
  10629. },
  10630. enumerable: true,
  10631. configurable: true
  10632. });
  10633. Object.defineProperty(Engine, "INCR", {
  10634. get: function () {
  10635. return Engine._INCR;
  10636. },
  10637. enumerable: true,
  10638. configurable: true
  10639. });
  10640. Object.defineProperty(Engine, "DECR", {
  10641. get: function () {
  10642. return Engine._DECR;
  10643. },
  10644. enumerable: true,
  10645. configurable: true
  10646. });
  10647. Object.defineProperty(Engine, "INVERT", {
  10648. get: function () {
  10649. return Engine._INVERT;
  10650. },
  10651. enumerable: true,
  10652. configurable: true
  10653. });
  10654. Object.defineProperty(Engine, "INCR_WRAP", {
  10655. get: function () {
  10656. return Engine._INCR_WRAP;
  10657. },
  10658. enumerable: true,
  10659. configurable: true
  10660. });
  10661. Object.defineProperty(Engine, "DECR_WRAP", {
  10662. get: function () {
  10663. return Engine._DECR_WRAP;
  10664. },
  10665. enumerable: true,
  10666. configurable: true
  10667. });
  10668. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10669. get: function () {
  10670. return Engine._ALPHA_DISABLE;
  10671. },
  10672. enumerable: true,
  10673. configurable: true
  10674. });
  10675. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10676. get: function () {
  10677. return Engine._ALPHA_ONEONE;
  10678. },
  10679. enumerable: true,
  10680. configurable: true
  10681. });
  10682. Object.defineProperty(Engine, "ALPHA_ADD", {
  10683. get: function () {
  10684. return Engine._ALPHA_ADD;
  10685. },
  10686. enumerable: true,
  10687. configurable: true
  10688. });
  10689. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10690. get: function () {
  10691. return Engine._ALPHA_COMBINE;
  10692. },
  10693. enumerable: true,
  10694. configurable: true
  10695. });
  10696. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10697. get: function () {
  10698. return Engine._ALPHA_SUBTRACT;
  10699. },
  10700. enumerable: true,
  10701. configurable: true
  10702. });
  10703. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10704. get: function () {
  10705. return Engine._ALPHA_MULTIPLY;
  10706. },
  10707. enumerable: true,
  10708. configurable: true
  10709. });
  10710. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10711. get: function () {
  10712. return Engine._ALPHA_MAXIMIZED;
  10713. },
  10714. enumerable: true,
  10715. configurable: true
  10716. });
  10717. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10718. get: function () {
  10719. return Engine._ALPHA_PREMULTIPLIED;
  10720. },
  10721. enumerable: true,
  10722. configurable: true
  10723. });
  10724. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10725. get: function () {
  10726. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10727. },
  10728. enumerable: true,
  10729. configurable: true
  10730. });
  10731. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10732. get: function () {
  10733. return Engine._ALPHA_INTERPOLATE;
  10734. },
  10735. enumerable: true,
  10736. configurable: true
  10737. });
  10738. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10739. get: function () {
  10740. return Engine._ALPHA_SCREENMODE;
  10741. },
  10742. enumerable: true,
  10743. configurable: true
  10744. });
  10745. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10746. get: function () {
  10747. return Engine._DELAYLOADSTATE_NONE;
  10748. },
  10749. enumerable: true,
  10750. configurable: true
  10751. });
  10752. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10753. get: function () {
  10754. return Engine._DELAYLOADSTATE_LOADED;
  10755. },
  10756. enumerable: true,
  10757. configurable: true
  10758. });
  10759. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10760. get: function () {
  10761. return Engine._DELAYLOADSTATE_LOADING;
  10762. },
  10763. enumerable: true,
  10764. configurable: true
  10765. });
  10766. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10767. get: function () {
  10768. return Engine._DELAYLOADSTATE_NOTLOADED;
  10769. },
  10770. enumerable: true,
  10771. configurable: true
  10772. });
  10773. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10774. get: function () {
  10775. return Engine._TEXTUREFORMAT_ALPHA;
  10776. },
  10777. enumerable: true,
  10778. configurable: true
  10779. });
  10780. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10781. get: function () {
  10782. return Engine._TEXTUREFORMAT_LUMINANCE;
  10783. },
  10784. enumerable: true,
  10785. configurable: true
  10786. });
  10787. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10788. get: function () {
  10789. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10790. },
  10791. enumerable: true,
  10792. configurable: true
  10793. });
  10794. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10795. get: function () {
  10796. return Engine._TEXTUREFORMAT_RGB;
  10797. },
  10798. enumerable: true,
  10799. configurable: true
  10800. });
  10801. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10802. get: function () {
  10803. return Engine._TEXTUREFORMAT_RGBA;
  10804. },
  10805. enumerable: true,
  10806. configurable: true
  10807. });
  10808. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10809. get: function () {
  10810. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10811. },
  10812. enumerable: true,
  10813. configurable: true
  10814. });
  10815. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10816. get: function () {
  10817. return Engine._TEXTURETYPE_FLOAT;
  10818. },
  10819. enumerable: true,
  10820. configurable: true
  10821. });
  10822. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10823. get: function () {
  10824. return Engine._TEXTURETYPE_HALF_FLOAT;
  10825. },
  10826. enumerable: true,
  10827. configurable: true
  10828. });
  10829. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10830. get: function () {
  10831. return Engine._SCALEMODE_FLOOR;
  10832. },
  10833. enumerable: true,
  10834. configurable: true
  10835. });
  10836. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10837. get: function () {
  10838. return Engine._SCALEMODE_NEAREST;
  10839. },
  10840. enumerable: true,
  10841. configurable: true
  10842. });
  10843. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10844. get: function () {
  10845. return Engine._SCALEMODE_CEILING;
  10846. },
  10847. enumerable: true,
  10848. configurable: true
  10849. });
  10850. Object.defineProperty(Engine, "Version", {
  10851. get: function () {
  10852. return "3.2.0-alpha7";
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10858. get: function () {
  10859. return this._vrExclusivePointerMode;
  10860. },
  10861. enumerable: true,
  10862. configurable: true
  10863. });
  10864. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10865. get: function () {
  10866. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10872. get: function () {
  10873. return this._webGLVersion < 2 || this.forcePOTTextures;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(Engine.prototype, "badOS", {
  10879. get: function () {
  10880. return this._badOS;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10886. get: function () {
  10887. return this._badDesktopOS;
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10893. get: function () {
  10894. return this._performanceMonitor;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10900. get: function () {
  10901. return this._texturesSupported;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10907. get: function () {
  10908. return this._textureFormatInUse;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(Engine.prototype, "currentViewport", {
  10914. get: function () {
  10915. return this._cachedViewport;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10921. // Empty texture
  10922. get: function () {
  10923. if (!this._emptyTexture) {
  10924. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10925. }
  10926. return this._emptyTexture;
  10927. },
  10928. enumerable: true,
  10929. configurable: true
  10930. });
  10931. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10932. get: function () {
  10933. if (!this._emptyTexture3D) {
  10934. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10935. }
  10936. return this._emptyTexture3D;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10942. get: function () {
  10943. if (!this._emptyCubeTexture) {
  10944. var faceData = new Uint8Array(4);
  10945. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10946. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10947. }
  10948. return this._emptyCubeTexture;
  10949. },
  10950. enumerable: true,
  10951. configurable: true
  10952. });
  10953. Engine.prototype._rebuildInternalTextures = function () {
  10954. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10955. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10956. var internalTexture = currentState_1[_i];
  10957. internalTexture._rebuild();
  10958. }
  10959. };
  10960. Engine.prototype._rebuildEffects = function () {
  10961. for (var key in this._compiledEffects) {
  10962. var effect = this._compiledEffects[key];
  10963. effect._prepareEffect();
  10964. }
  10965. BABYLON.Effect.ResetCache();
  10966. };
  10967. Engine.prototype._rebuildBuffers = function () {
  10968. // Index / Vertex
  10969. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10970. var scene = _a[_i];
  10971. scene.resetCachedMaterial();
  10972. scene._rebuildGeometries();
  10973. scene._rebuildTextures();
  10974. }
  10975. // Uniforms
  10976. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10977. var uniformBuffer = _c[_b];
  10978. uniformBuffer._rebuild();
  10979. }
  10980. };
  10981. Engine.prototype._initGLContext = function () {
  10982. // Caps
  10983. this._caps = new EngineCapabilities();
  10984. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10985. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10986. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10987. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10988. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10989. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10990. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10991. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10992. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10993. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10994. // Infos
  10995. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10996. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10997. if (rendererInfo != null) {
  10998. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10999. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11000. }
  11001. if (!this._glVendor) {
  11002. this._glVendor = "Unknown vendor";
  11003. }
  11004. if (!this._glRenderer) {
  11005. this._glRenderer = "Unknown renderer";
  11006. }
  11007. // Constants
  11008. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11009. if (this._gl.RGBA16F !== 0x881A) {
  11010. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11011. }
  11012. if (this._gl.RGBA32F !== 0x8814) {
  11013. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11014. }
  11015. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11016. this._gl.DEPTH24_STENCIL8 = 35056;
  11017. }
  11018. // Extensions
  11019. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11020. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11021. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11022. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11023. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11024. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11025. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11026. 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');
  11027. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11028. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11029. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11030. this._caps.highPrecisionShaderSupported = true;
  11031. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11032. if (this._caps.timerQuery) {
  11033. if (this._webGLVersion === 1) {
  11034. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11035. }
  11036. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11037. }
  11038. // Checks if some of the format renders first to allow the use of webgl inspector.
  11039. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11040. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11041. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11042. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11043. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11044. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11045. if (this._webGLVersion > 1) {
  11046. this._gl.HALF_FLOAT_OES = 0x140B;
  11047. }
  11048. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11049. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11050. // Draw buffers
  11051. if (this._webGLVersion > 1) {
  11052. this._caps.drawBuffersExtension = true;
  11053. }
  11054. else {
  11055. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11056. if (drawBuffersExtension !== null) {
  11057. this._caps.drawBuffersExtension = true;
  11058. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11059. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11060. for (var i = 0; i < 16; i++) {
  11061. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11062. }
  11063. }
  11064. else {
  11065. this._caps.drawBuffersExtension = false;
  11066. }
  11067. }
  11068. // Depth Texture
  11069. if (this._webGLVersion > 1) {
  11070. this._caps.depthTextureExtension = true;
  11071. }
  11072. else {
  11073. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11074. if (depthTextureExtension != null) {
  11075. this._caps.depthTextureExtension = true;
  11076. }
  11077. }
  11078. // Vertex array object
  11079. if (this._webGLVersion > 1) {
  11080. this._caps.vertexArrayObject = true;
  11081. }
  11082. else {
  11083. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11084. if (vertexArrayObjectExtension != null) {
  11085. this._caps.vertexArrayObject = true;
  11086. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11087. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11088. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11089. }
  11090. else {
  11091. this._caps.vertexArrayObject = false;
  11092. }
  11093. }
  11094. // Instances count
  11095. if (this._webGLVersion > 1) {
  11096. this._caps.instancedArrays = true;
  11097. }
  11098. else {
  11099. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11100. if (instanceExtension != null) {
  11101. this._caps.instancedArrays = true;
  11102. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11103. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11104. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11105. }
  11106. else {
  11107. this._caps.instancedArrays = false;
  11108. }
  11109. }
  11110. // Intelligently add supported compressed formats in order to check for.
  11111. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11112. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11113. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11114. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11115. if (this._caps.astc)
  11116. this.texturesSupported.push('-astc.ktx');
  11117. if (this._caps.s3tc)
  11118. this.texturesSupported.push('-dxt.ktx');
  11119. if (this._caps.pvrtc)
  11120. this.texturesSupported.push('-pvrtc.ktx');
  11121. if (this._caps.etc2)
  11122. this.texturesSupported.push('-etc2.ktx');
  11123. if (this._caps.etc1)
  11124. this.texturesSupported.push('-etc1.ktx');
  11125. if (this._gl.getShaderPrecisionFormat) {
  11126. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11127. if (highp) {
  11128. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11129. }
  11130. }
  11131. // Depth buffer
  11132. this.setDepthBuffer(true);
  11133. this.setDepthFunctionToLessOrEqual();
  11134. this.setDepthWrite(true);
  11135. // Texture maps
  11136. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11137. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11138. this._nextFreeTextureSlots.push(slot);
  11139. }
  11140. };
  11141. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11142. get: function () {
  11143. return this._webGLVersion;
  11144. },
  11145. enumerable: true,
  11146. configurable: true
  11147. });
  11148. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11149. /**
  11150. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11151. */
  11152. get: function () {
  11153. return this._isStencilEnable;
  11154. },
  11155. enumerable: true,
  11156. configurable: true
  11157. });
  11158. Engine.prototype._prepareWorkingCanvas = function () {
  11159. if (this._workingCanvas) {
  11160. return;
  11161. }
  11162. this._workingCanvas = document.createElement("canvas");
  11163. var context = this._workingCanvas.getContext("2d");
  11164. if (context) {
  11165. this._workingContext = context;
  11166. }
  11167. };
  11168. Engine.prototype.resetTextureCache = function () {
  11169. for (var key in this._boundTexturesCache) {
  11170. var boundTexture = this._boundTexturesCache[key];
  11171. if (boundTexture) {
  11172. this._removeDesignatedSlot(boundTexture);
  11173. }
  11174. this._boundTexturesCache[key] = null;
  11175. }
  11176. if (!this.disableTextureBindingOptimization) {
  11177. this._nextFreeTextureSlots = [];
  11178. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11179. this._nextFreeTextureSlots.push(slot);
  11180. }
  11181. }
  11182. this._currentTextureChannel = -1;
  11183. };
  11184. Engine.prototype.isDeterministicLockStep = function () {
  11185. return this._deterministicLockstep;
  11186. };
  11187. Engine.prototype.getLockstepMaxSteps = function () {
  11188. return this._lockstepMaxSteps;
  11189. };
  11190. Engine.prototype.getGlInfo = function () {
  11191. return {
  11192. vendor: this._glVendor,
  11193. renderer: this._glRenderer,
  11194. version: this._glVersion
  11195. };
  11196. };
  11197. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11198. if (useScreen === void 0) { useScreen = false; }
  11199. var viewport = camera.viewport;
  11200. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11201. };
  11202. Engine.prototype.getRenderWidth = function (useScreen) {
  11203. if (useScreen === void 0) { useScreen = false; }
  11204. if (!useScreen && this._currentRenderTarget) {
  11205. return this._currentRenderTarget.width;
  11206. }
  11207. return this._gl.drawingBufferWidth;
  11208. };
  11209. Engine.prototype.getRenderHeight = function (useScreen) {
  11210. if (useScreen === void 0) { useScreen = false; }
  11211. if (!useScreen && this._currentRenderTarget) {
  11212. return this._currentRenderTarget.height;
  11213. }
  11214. return this._gl.drawingBufferHeight;
  11215. };
  11216. Engine.prototype.getRenderingCanvas = function () {
  11217. return this._renderingCanvas;
  11218. };
  11219. Engine.prototype.getRenderingCanvasClientRect = function () {
  11220. if (!this._renderingCanvas) {
  11221. return null;
  11222. }
  11223. return this._renderingCanvas.getBoundingClientRect();
  11224. };
  11225. Engine.prototype.setHardwareScalingLevel = function (level) {
  11226. this._hardwareScalingLevel = level;
  11227. this.resize();
  11228. };
  11229. Engine.prototype.getHardwareScalingLevel = function () {
  11230. return this._hardwareScalingLevel;
  11231. };
  11232. Engine.prototype.getLoadedTexturesCache = function () {
  11233. return this._internalTexturesCache;
  11234. };
  11235. Engine.prototype.getCaps = function () {
  11236. return this._caps;
  11237. };
  11238. Object.defineProperty(Engine.prototype, "drawCalls", {
  11239. /** The number of draw calls submitted last frame */
  11240. get: function () {
  11241. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11242. return 0;
  11243. },
  11244. enumerable: true,
  11245. configurable: true
  11246. });
  11247. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11248. get: function () {
  11249. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11250. return null;
  11251. },
  11252. enumerable: true,
  11253. configurable: true
  11254. });
  11255. Engine.prototype.getDepthFunction = function () {
  11256. return this._depthCullingState.depthFunc;
  11257. };
  11258. Engine.prototype.setDepthFunction = function (depthFunc) {
  11259. this._depthCullingState.depthFunc = depthFunc;
  11260. };
  11261. Engine.prototype.setDepthFunctionToGreater = function () {
  11262. this._depthCullingState.depthFunc = this._gl.GREATER;
  11263. };
  11264. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11265. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11266. };
  11267. Engine.prototype.setDepthFunctionToLess = function () {
  11268. this._depthCullingState.depthFunc = this._gl.LESS;
  11269. };
  11270. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11271. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11272. };
  11273. Engine.prototype.getStencilBuffer = function () {
  11274. return this._stencilState.stencilTest;
  11275. };
  11276. Engine.prototype.setStencilBuffer = function (enable) {
  11277. this._stencilState.stencilTest = enable;
  11278. };
  11279. Engine.prototype.getStencilMask = function () {
  11280. return this._stencilState.stencilMask;
  11281. };
  11282. Engine.prototype.setStencilMask = function (mask) {
  11283. this._stencilState.stencilMask = mask;
  11284. };
  11285. Engine.prototype.getStencilFunction = function () {
  11286. return this._stencilState.stencilFunc;
  11287. };
  11288. Engine.prototype.getStencilFunctionReference = function () {
  11289. return this._stencilState.stencilFuncRef;
  11290. };
  11291. Engine.prototype.getStencilFunctionMask = function () {
  11292. return this._stencilState.stencilFuncMask;
  11293. };
  11294. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11295. this._stencilState.stencilFunc = stencilFunc;
  11296. };
  11297. Engine.prototype.setStencilFunctionReference = function (reference) {
  11298. this._stencilState.stencilFuncRef = reference;
  11299. };
  11300. Engine.prototype.setStencilFunctionMask = function (mask) {
  11301. this._stencilState.stencilFuncMask = mask;
  11302. };
  11303. Engine.prototype.getStencilOperationFail = function () {
  11304. return this._stencilState.stencilOpStencilFail;
  11305. };
  11306. Engine.prototype.getStencilOperationDepthFail = function () {
  11307. return this._stencilState.stencilOpDepthFail;
  11308. };
  11309. Engine.prototype.getStencilOperationPass = function () {
  11310. return this._stencilState.stencilOpStencilDepthPass;
  11311. };
  11312. Engine.prototype.setStencilOperationFail = function (operation) {
  11313. this._stencilState.stencilOpStencilFail = operation;
  11314. };
  11315. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11316. this._stencilState.stencilOpDepthFail = operation;
  11317. };
  11318. Engine.prototype.setStencilOperationPass = function (operation) {
  11319. this._stencilState.stencilOpStencilDepthPass = operation;
  11320. };
  11321. Engine.prototype.setDitheringState = function (value) {
  11322. if (value) {
  11323. this._gl.enable(this._gl.DITHER);
  11324. }
  11325. else {
  11326. this._gl.disable(this._gl.DITHER);
  11327. }
  11328. };
  11329. Engine.prototype.setRasterizerState = function (value) {
  11330. if (value) {
  11331. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11332. }
  11333. else {
  11334. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11335. }
  11336. };
  11337. /**
  11338. * stop executing a render loop function and remove it from the execution array
  11339. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11340. */
  11341. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11342. if (!renderFunction) {
  11343. this._activeRenderLoops = [];
  11344. return;
  11345. }
  11346. var index = this._activeRenderLoops.indexOf(renderFunction);
  11347. if (index >= 0) {
  11348. this._activeRenderLoops.splice(index, 1);
  11349. }
  11350. };
  11351. Engine.prototype._renderLoop = function () {
  11352. if (!this._contextWasLost) {
  11353. var shouldRender = true;
  11354. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11355. shouldRender = false;
  11356. }
  11357. if (shouldRender) {
  11358. // Start new frame
  11359. this.beginFrame();
  11360. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11361. var renderFunction = this._activeRenderLoops[index];
  11362. renderFunction();
  11363. }
  11364. // Present
  11365. this.endFrame();
  11366. }
  11367. }
  11368. if (this._activeRenderLoops.length > 0) {
  11369. // Register new frame
  11370. var requester = null;
  11371. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11372. requester = this._vrDisplay;
  11373. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11374. }
  11375. else {
  11376. this._renderingQueueLaunched = false;
  11377. }
  11378. };
  11379. /**
  11380. * Register and execute a render loop. The engine can have more than one render function.
  11381. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11382. * @example
  11383. * engine.runRenderLoop(function () {
  11384. * scene.render()
  11385. * })
  11386. */
  11387. Engine.prototype.runRenderLoop = function (renderFunction) {
  11388. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11389. return;
  11390. }
  11391. this._activeRenderLoops.push(renderFunction);
  11392. if (!this._renderingQueueLaunched) {
  11393. this._renderingQueueLaunched = true;
  11394. this._bindedRenderFunction = this._renderLoop.bind(this);
  11395. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11396. }
  11397. };
  11398. /**
  11399. * Toggle full screen mode.
  11400. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11401. * @param {any} options - an options object to be sent to the requestFullscreen function
  11402. */
  11403. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11404. if (this.isFullscreen) {
  11405. BABYLON.Tools.ExitFullscreen();
  11406. }
  11407. else {
  11408. this._pointerLockRequested = requestPointerLock;
  11409. if (this._renderingCanvas) {
  11410. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11411. }
  11412. }
  11413. };
  11414. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11415. if (stencil === void 0) { stencil = false; }
  11416. this.applyStates();
  11417. var mode = 0;
  11418. if (backBuffer && color) {
  11419. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11420. mode |= this._gl.COLOR_BUFFER_BIT;
  11421. }
  11422. if (depth) {
  11423. this._gl.clearDepth(1.0);
  11424. mode |= this._gl.DEPTH_BUFFER_BIT;
  11425. }
  11426. if (stencil) {
  11427. this._gl.clearStencil(0);
  11428. mode |= this._gl.STENCIL_BUFFER_BIT;
  11429. }
  11430. this._gl.clear(mode);
  11431. };
  11432. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11433. var gl = this._gl;
  11434. // Save state
  11435. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11436. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11437. // Change state
  11438. gl.enable(gl.SCISSOR_TEST);
  11439. gl.scissor(x, y, width, height);
  11440. // Clear
  11441. this.clear(clearColor, true, true, true);
  11442. // Restore state
  11443. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11444. if (curScissor === true) {
  11445. gl.enable(gl.SCISSOR_TEST);
  11446. }
  11447. else {
  11448. gl.disable(gl.SCISSOR_TEST);
  11449. }
  11450. };
  11451. /**
  11452. * Set the WebGL's viewport
  11453. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11454. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11455. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11456. */
  11457. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11458. var width = requiredWidth || this.getRenderWidth();
  11459. var height = requiredHeight || this.getRenderHeight();
  11460. var x = viewport.x || 0;
  11461. var y = viewport.y || 0;
  11462. this._cachedViewport = viewport;
  11463. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11464. };
  11465. /**
  11466. * Directly set the WebGL Viewport
  11467. * The x, y, width & height are directly passed to the WebGL call
  11468. * @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.
  11469. */
  11470. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11471. var currentViewport = this._cachedViewport;
  11472. this._cachedViewport = null;
  11473. this._gl.viewport(x, y, width, height);
  11474. return currentViewport;
  11475. };
  11476. Engine.prototype.beginFrame = function () {
  11477. this.onBeginFrameObservable.notifyObservers(this);
  11478. this._measureFps();
  11479. };
  11480. Engine.prototype.endFrame = function () {
  11481. //force a flush in case we are using a bad OS.
  11482. if (this._badOS) {
  11483. this.flushFramebuffer();
  11484. }
  11485. //submit frame to the vr device, if enabled
  11486. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11487. // TODO: We should only submit the frame if we read frameData successfully.
  11488. this._vrDisplay.submitFrame();
  11489. }
  11490. this.onEndFrameObservable.notifyObservers(this);
  11491. };
  11492. /**
  11493. * resize the view according to the canvas' size.
  11494. * @example
  11495. * window.addEventListener("resize", function () {
  11496. * engine.resize();
  11497. * });
  11498. */
  11499. Engine.prototype.resize = function () {
  11500. // We're not resizing the size of the canvas while in VR mode & presenting
  11501. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11502. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11503. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11504. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11505. }
  11506. };
  11507. /**
  11508. * force a specific size of the canvas
  11509. * @param {number} width - the new canvas' width
  11510. * @param {number} height - the new canvas' height
  11511. */
  11512. Engine.prototype.setSize = function (width, height) {
  11513. if (!this._renderingCanvas) {
  11514. return;
  11515. }
  11516. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11517. return;
  11518. }
  11519. this._renderingCanvas.width = width;
  11520. this._renderingCanvas.height = height;
  11521. for (var index = 0; index < this.scenes.length; index++) {
  11522. var scene = this.scenes[index];
  11523. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11524. var cam = scene.cameras[camIndex];
  11525. cam._currentRenderId = 0;
  11526. }
  11527. }
  11528. if (this.onResizeObservable.hasObservers) {
  11529. this.onResizeObservable.notifyObservers(this);
  11530. }
  11531. };
  11532. // WebVR functions
  11533. Engine.prototype.isVRDevicePresent = function () {
  11534. return !!this._vrDisplay;
  11535. };
  11536. Engine.prototype.getVRDevice = function () {
  11537. return this._vrDisplay;
  11538. };
  11539. Engine.prototype.initWebVR = function () {
  11540. var _this = this;
  11541. var notifyObservers = function () {
  11542. var eventArgs = {
  11543. vrDisplay: _this._vrDisplay,
  11544. vrSupported: _this._vrSupported
  11545. };
  11546. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11547. };
  11548. if (!this._onVrDisplayConnect) {
  11549. this._onVrDisplayConnect = function (event) {
  11550. _this._vrDisplay = event.display;
  11551. notifyObservers();
  11552. };
  11553. this._onVrDisplayDisconnect = function () {
  11554. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11555. _this._vrDisplay = undefined;
  11556. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11557. notifyObservers();
  11558. };
  11559. this._onVrDisplayPresentChange = function () {
  11560. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11561. };
  11562. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11563. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11564. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11565. }
  11566. this._getVRDisplays(notifyObservers);
  11567. return this.onVRDisplayChangedObservable;
  11568. };
  11569. Engine.prototype.enableVR = function () {
  11570. var _this = this;
  11571. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11572. var onResolved = function () {
  11573. _this.onVRRequestPresentComplete.notifyObservers(true);
  11574. _this._onVRFullScreenTriggered();
  11575. };
  11576. var onRejected = function () {
  11577. _this.onVRRequestPresentComplete.notifyObservers(false);
  11578. };
  11579. this.onVRRequestPresentStart.notifyObservers(this);
  11580. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11581. }
  11582. };
  11583. Engine.prototype.disableVR = function () {
  11584. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11585. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11586. }
  11587. };
  11588. Engine.prototype._getVRDisplays = function (callback) {
  11589. var _this = this;
  11590. var getWebVRDevices = function (devices) {
  11591. _this._vrSupported = true;
  11592. // note that devices may actually be an empty array. This is fine;
  11593. // we expect this._vrDisplay to be undefined in this case.
  11594. return _this._vrDisplay = devices[0];
  11595. };
  11596. if (navigator.getVRDisplays) {
  11597. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  11598. // TODO: System CANNOT support WebVR, despite API presence.
  11599. _this._vrSupported = false;
  11600. callback();
  11601. });
  11602. }
  11603. else {
  11604. // TODO: Browser does not support WebVR
  11605. this._vrDisplay = undefined;
  11606. this._vrSupported = false;
  11607. callback();
  11608. }
  11609. };
  11610. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11611. if (this._currentRenderTarget) {
  11612. this.unBindFramebuffer(this._currentRenderTarget);
  11613. }
  11614. this._currentRenderTarget = texture;
  11615. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11616. var gl = this._gl;
  11617. if (texture.isCube) {
  11618. if (faceIndex === undefined) {
  11619. faceIndex = 0;
  11620. }
  11621. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11622. }
  11623. if (this._cachedViewport && !forceFullscreenViewport) {
  11624. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11625. }
  11626. else {
  11627. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11628. }
  11629. this.wipeCaches();
  11630. };
  11631. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11632. if (this._currentFramebuffer !== framebuffer) {
  11633. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11634. this._currentFramebuffer = framebuffer;
  11635. }
  11636. };
  11637. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11638. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11639. this._currentRenderTarget = null;
  11640. // If MSAA, we need to bitblt back to main texture
  11641. var gl = this._gl;
  11642. if (texture._MSAAFramebuffer) {
  11643. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11644. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11645. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11646. }
  11647. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11648. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11649. gl.generateMipmap(gl.TEXTURE_2D);
  11650. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11651. }
  11652. if (onBeforeUnbind) {
  11653. if (texture._MSAAFramebuffer) {
  11654. // Bind the correct framebuffer
  11655. this.bindUnboundFramebuffer(texture._framebuffer);
  11656. }
  11657. onBeforeUnbind();
  11658. }
  11659. this.bindUnboundFramebuffer(null);
  11660. };
  11661. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11662. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11663. this._currentRenderTarget = null;
  11664. // If MSAA, we need to bitblt back to main texture
  11665. var gl = this._gl;
  11666. if (textures[0]._MSAAFramebuffer) {
  11667. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11668. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11669. var attachments = textures[0]._attachments;
  11670. if (!attachments) {
  11671. attachments = new Array(textures.length);
  11672. textures[0]._attachments = attachments;
  11673. }
  11674. for (var i = 0; i < textures.length; i++) {
  11675. var texture = textures[i];
  11676. for (var j = 0; j < attachments.length; j++) {
  11677. attachments[j] = gl.NONE;
  11678. }
  11679. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11680. gl.readBuffer(attachments[i]);
  11681. gl.drawBuffers(attachments);
  11682. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11683. }
  11684. for (var i = 0; i < attachments.length; i++) {
  11685. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11686. }
  11687. gl.drawBuffers(attachments);
  11688. }
  11689. for (var i = 0; i < textures.length; i++) {
  11690. var texture = textures[i];
  11691. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11692. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11693. gl.generateMipmap(gl.TEXTURE_2D);
  11694. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11695. }
  11696. }
  11697. if (onBeforeUnbind) {
  11698. if (textures[0]._MSAAFramebuffer) {
  11699. // Bind the correct framebuffer
  11700. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11701. }
  11702. onBeforeUnbind();
  11703. }
  11704. this.bindUnboundFramebuffer(null);
  11705. };
  11706. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11707. if (texture.generateMipMaps) {
  11708. var gl = this._gl;
  11709. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11710. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11711. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11712. }
  11713. };
  11714. Engine.prototype.flushFramebuffer = function () {
  11715. this._gl.flush();
  11716. };
  11717. Engine.prototype.restoreDefaultFramebuffer = function () {
  11718. if (this._currentRenderTarget) {
  11719. this.unBindFramebuffer(this._currentRenderTarget);
  11720. }
  11721. else {
  11722. this.bindUnboundFramebuffer(null);
  11723. }
  11724. if (this._cachedViewport) {
  11725. this.setViewport(this._cachedViewport);
  11726. }
  11727. this.wipeCaches();
  11728. };
  11729. // UBOs
  11730. Engine.prototype.createUniformBuffer = function (elements) {
  11731. var ubo = this._gl.createBuffer();
  11732. if (!ubo) {
  11733. throw new Error("Unable to create uniform buffer");
  11734. }
  11735. this.bindUniformBuffer(ubo);
  11736. if (elements instanceof Float32Array) {
  11737. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11738. }
  11739. else {
  11740. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11741. }
  11742. this.bindUniformBuffer(null);
  11743. ubo.references = 1;
  11744. return ubo;
  11745. };
  11746. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11747. var ubo = this._gl.createBuffer();
  11748. if (!ubo) {
  11749. throw new Error("Unable to create dynamic uniform buffer");
  11750. }
  11751. this.bindUniformBuffer(ubo);
  11752. if (elements instanceof Float32Array) {
  11753. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11754. }
  11755. else {
  11756. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11757. }
  11758. this.bindUniformBuffer(null);
  11759. ubo.references = 1;
  11760. return ubo;
  11761. };
  11762. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11763. this.bindUniformBuffer(uniformBuffer);
  11764. if (offset === undefined) {
  11765. offset = 0;
  11766. }
  11767. if (count === undefined) {
  11768. if (elements instanceof Float32Array) {
  11769. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11770. }
  11771. else {
  11772. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11773. }
  11774. }
  11775. else {
  11776. if (elements instanceof Float32Array) {
  11777. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11778. }
  11779. else {
  11780. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11781. }
  11782. }
  11783. this.bindUniformBuffer(null);
  11784. };
  11785. // VBOs
  11786. Engine.prototype._resetVertexBufferBinding = function () {
  11787. this.bindArrayBuffer(null);
  11788. this._cachedVertexBuffers = null;
  11789. };
  11790. Engine.prototype.createVertexBuffer = function (vertices) {
  11791. var vbo = this._gl.createBuffer();
  11792. if (!vbo) {
  11793. throw new Error("Unable to create vertex buffer");
  11794. }
  11795. this.bindArrayBuffer(vbo);
  11796. if (vertices instanceof Float32Array) {
  11797. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11798. }
  11799. else {
  11800. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11801. }
  11802. this._resetVertexBufferBinding();
  11803. vbo.references = 1;
  11804. return vbo;
  11805. };
  11806. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11807. var vbo = this._gl.createBuffer();
  11808. if (!vbo) {
  11809. throw new Error("Unable to create dynamic vertex buffer");
  11810. }
  11811. this.bindArrayBuffer(vbo);
  11812. if (vertices instanceof Float32Array) {
  11813. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11814. }
  11815. else {
  11816. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11817. }
  11818. this._resetVertexBufferBinding();
  11819. vbo.references = 1;
  11820. return vbo;
  11821. };
  11822. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11823. if (offset === void 0) { offset = 0; }
  11824. // Force cache update
  11825. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11826. this.bindIndexBuffer(indexBuffer);
  11827. var arrayBuffer;
  11828. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11829. arrayBuffer = indices;
  11830. }
  11831. else {
  11832. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11833. }
  11834. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11835. this._resetIndexBufferBinding();
  11836. };
  11837. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11838. this.bindArrayBuffer(vertexBuffer);
  11839. if (offset === undefined) {
  11840. offset = 0;
  11841. }
  11842. if (count === undefined) {
  11843. if (vertices instanceof Float32Array) {
  11844. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11845. }
  11846. else {
  11847. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11848. }
  11849. }
  11850. else {
  11851. if (vertices instanceof Float32Array) {
  11852. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11853. }
  11854. else {
  11855. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11856. }
  11857. }
  11858. this._resetVertexBufferBinding();
  11859. };
  11860. Engine.prototype._resetIndexBufferBinding = function () {
  11861. this.bindIndexBuffer(null);
  11862. this._cachedIndexBuffer = null;
  11863. };
  11864. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11865. var vbo = this._gl.createBuffer();
  11866. if (!vbo) {
  11867. throw new Error("Unable to create index buffer");
  11868. }
  11869. this.bindIndexBuffer(vbo);
  11870. // Check for 32 bits indices
  11871. var arrayBuffer;
  11872. var need32Bits = false;
  11873. if (indices instanceof Uint16Array) {
  11874. arrayBuffer = indices;
  11875. }
  11876. else {
  11877. //check 32 bit support
  11878. if (this._caps.uintIndices) {
  11879. if (indices instanceof Uint32Array) {
  11880. arrayBuffer = indices;
  11881. need32Bits = true;
  11882. }
  11883. else {
  11884. //number[] or Int32Array, check if 32 bit is necessary
  11885. for (var index = 0; index < indices.length; index++) {
  11886. if (indices[index] > 65535) {
  11887. need32Bits = true;
  11888. break;
  11889. }
  11890. }
  11891. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11892. }
  11893. }
  11894. else {
  11895. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11896. arrayBuffer = new Uint16Array(indices);
  11897. }
  11898. }
  11899. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11900. this._resetIndexBufferBinding();
  11901. vbo.references = 1;
  11902. vbo.is32Bits = need32Bits;
  11903. return vbo;
  11904. };
  11905. Engine.prototype.bindArrayBuffer = function (buffer) {
  11906. if (!this._vaoRecordInProgress) {
  11907. this._unbindVertexArrayObject();
  11908. }
  11909. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11910. };
  11911. Engine.prototype.bindUniformBuffer = function (buffer) {
  11912. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11913. };
  11914. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11915. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11916. };
  11917. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11918. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11919. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11920. };
  11921. ;
  11922. Engine.prototype.bindIndexBuffer = function (buffer) {
  11923. if (!this._vaoRecordInProgress) {
  11924. this._unbindVertexArrayObject();
  11925. }
  11926. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11927. };
  11928. Engine.prototype.bindBuffer = function (buffer, target) {
  11929. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11930. this._gl.bindBuffer(target, buffer);
  11931. this._currentBoundBuffer[target] = buffer;
  11932. }
  11933. };
  11934. Engine.prototype.updateArrayBuffer = function (data) {
  11935. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11936. };
  11937. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11938. var pointer = this._currentBufferPointers[indx];
  11939. var changed = false;
  11940. if (!pointer.active) {
  11941. changed = true;
  11942. pointer.active = true;
  11943. pointer.index = indx;
  11944. pointer.size = size;
  11945. pointer.type = type;
  11946. pointer.normalized = normalized;
  11947. pointer.stride = stride;
  11948. pointer.offset = offset;
  11949. pointer.buffer = buffer;
  11950. }
  11951. else {
  11952. if (pointer.buffer !== buffer) {
  11953. pointer.buffer = buffer;
  11954. changed = true;
  11955. }
  11956. if (pointer.size !== size) {
  11957. pointer.size = size;
  11958. changed = true;
  11959. }
  11960. if (pointer.type !== type) {
  11961. pointer.type = type;
  11962. changed = true;
  11963. }
  11964. if (pointer.normalized !== normalized) {
  11965. pointer.normalized = normalized;
  11966. changed = true;
  11967. }
  11968. if (pointer.stride !== stride) {
  11969. pointer.stride = stride;
  11970. changed = true;
  11971. }
  11972. if (pointer.offset !== offset) {
  11973. pointer.offset = offset;
  11974. changed = true;
  11975. }
  11976. }
  11977. if (changed || this._vaoRecordInProgress) {
  11978. this.bindArrayBuffer(buffer);
  11979. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11980. }
  11981. };
  11982. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11983. if (indexBuffer == null) {
  11984. return;
  11985. }
  11986. if (this._cachedIndexBuffer !== indexBuffer) {
  11987. this._cachedIndexBuffer = indexBuffer;
  11988. this.bindIndexBuffer(indexBuffer);
  11989. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11990. }
  11991. };
  11992. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11993. var attributes = effect.getAttributesNames();
  11994. if (!this._vaoRecordInProgress) {
  11995. this._unbindVertexArrayObject();
  11996. }
  11997. this.unbindAllAttributes();
  11998. for (var index = 0; index < attributes.length; index++) {
  11999. var order = effect.getAttributeLocation(index);
  12000. if (order >= 0) {
  12001. var vertexBuffer = vertexBuffers[attributes[index]];
  12002. if (!vertexBuffer) {
  12003. continue;
  12004. }
  12005. this._gl.enableVertexAttribArray(order);
  12006. if (!this._vaoRecordInProgress) {
  12007. this._vertexAttribArraysEnabled[order] = true;
  12008. }
  12009. var buffer = vertexBuffer.getBuffer();
  12010. if (buffer) {
  12011. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12012. if (vertexBuffer.getIsInstanced()) {
  12013. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12014. if (!this._vaoRecordInProgress) {
  12015. this._currentInstanceLocations.push(order);
  12016. this._currentInstanceBuffers.push(buffer);
  12017. }
  12018. }
  12019. }
  12020. }
  12021. }
  12022. };
  12023. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12024. var vao = this._gl.createVertexArray();
  12025. this._vaoRecordInProgress = true;
  12026. this._gl.bindVertexArray(vao);
  12027. this._mustWipeVertexAttributes = true;
  12028. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12029. this.bindIndexBuffer(indexBuffer);
  12030. this._vaoRecordInProgress = false;
  12031. this._gl.bindVertexArray(null);
  12032. return vao;
  12033. };
  12034. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12035. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12036. this._cachedVertexArrayObject = vertexArrayObject;
  12037. this._gl.bindVertexArray(vertexArrayObject);
  12038. this._cachedVertexBuffers = null;
  12039. this._cachedIndexBuffer = null;
  12040. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12041. this._mustWipeVertexAttributes = true;
  12042. }
  12043. };
  12044. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12045. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12046. this._cachedVertexBuffers = vertexBuffer;
  12047. this._cachedEffectForVertexBuffers = effect;
  12048. var attributesCount = effect.getAttributesCount();
  12049. this._unbindVertexArrayObject();
  12050. this.unbindAllAttributes();
  12051. var offset = 0;
  12052. for (var index = 0; index < attributesCount; index++) {
  12053. if (index < vertexDeclaration.length) {
  12054. var order = effect.getAttributeLocation(index);
  12055. if (order >= 0) {
  12056. this._gl.enableVertexAttribArray(order);
  12057. this._vertexAttribArraysEnabled[order] = true;
  12058. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12059. }
  12060. offset += vertexDeclaration[index] * 4;
  12061. }
  12062. }
  12063. }
  12064. this._bindIndexBufferWithCache(indexBuffer);
  12065. };
  12066. Engine.prototype._unbindVertexArrayObject = function () {
  12067. if (!this._cachedVertexArrayObject) {
  12068. return;
  12069. }
  12070. this._cachedVertexArrayObject = null;
  12071. this._gl.bindVertexArray(null);
  12072. };
  12073. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12074. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12075. this._cachedVertexBuffers = vertexBuffers;
  12076. this._cachedEffectForVertexBuffers = effect;
  12077. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12078. }
  12079. this._bindIndexBufferWithCache(indexBuffer);
  12080. };
  12081. Engine.prototype.unbindInstanceAttributes = function () {
  12082. var boundBuffer;
  12083. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12084. var instancesBuffer = this._currentInstanceBuffers[i];
  12085. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12086. boundBuffer = instancesBuffer;
  12087. this.bindArrayBuffer(instancesBuffer);
  12088. }
  12089. var offsetLocation = this._currentInstanceLocations[i];
  12090. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12091. }
  12092. this._currentInstanceBuffers.length = 0;
  12093. this._currentInstanceLocations.length = 0;
  12094. };
  12095. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12096. this._gl.deleteVertexArray(vao);
  12097. };
  12098. Engine.prototype._releaseBuffer = function (buffer) {
  12099. buffer.references--;
  12100. if (buffer.references === 0) {
  12101. this._gl.deleteBuffer(buffer);
  12102. return true;
  12103. }
  12104. return false;
  12105. };
  12106. Engine.prototype.createInstancesBuffer = function (capacity) {
  12107. var buffer = this._gl.createBuffer();
  12108. if (!buffer) {
  12109. throw new Error("Unable to create instance buffer");
  12110. }
  12111. buffer.capacity = capacity;
  12112. this.bindArrayBuffer(buffer);
  12113. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12114. return buffer;
  12115. };
  12116. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12117. this._gl.deleteBuffer(buffer);
  12118. };
  12119. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12120. this.bindArrayBuffer(instancesBuffer);
  12121. if (data) {
  12122. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12123. }
  12124. if (offsetLocations[0].index !== undefined) {
  12125. var stride = 0;
  12126. for (var i = 0; i < offsetLocations.length; i++) {
  12127. var ai = offsetLocations[i];
  12128. stride += ai.attributeSize * 4;
  12129. }
  12130. for (var i = 0; i < offsetLocations.length; i++) {
  12131. var ai = offsetLocations[i];
  12132. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12133. this._gl.enableVertexAttribArray(ai.index);
  12134. this._vertexAttribArraysEnabled[ai.index] = true;
  12135. }
  12136. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12137. this._gl.vertexAttribDivisor(ai.index, 1);
  12138. this._currentInstanceLocations.push(ai.index);
  12139. this._currentInstanceBuffers.push(instancesBuffer);
  12140. }
  12141. }
  12142. else {
  12143. for (var index = 0; index < 4; index++) {
  12144. var offsetLocation = offsetLocations[index];
  12145. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12146. this._gl.enableVertexAttribArray(offsetLocation);
  12147. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12148. }
  12149. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12150. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12151. this._currentInstanceLocations.push(offsetLocation);
  12152. this._currentInstanceBuffers.push(instancesBuffer);
  12153. }
  12154. }
  12155. };
  12156. Engine.prototype.applyStates = function () {
  12157. this._depthCullingState.apply(this._gl);
  12158. this._stencilState.apply(this._gl);
  12159. this._alphaState.apply(this._gl);
  12160. };
  12161. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12162. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12163. };
  12164. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12165. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12166. };
  12167. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12168. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12169. };
  12170. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12171. // Apply states
  12172. this.applyStates();
  12173. this._drawCalls.addCount(1, false);
  12174. // Render
  12175. var drawMode = this.DrawMode(fillMode);
  12176. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12177. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12178. if (instancesCount) {
  12179. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12180. }
  12181. else {
  12182. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12183. }
  12184. };
  12185. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12186. // Apply states
  12187. this.applyStates();
  12188. this._drawCalls.addCount(1, false);
  12189. var drawMode = this.DrawMode(fillMode);
  12190. if (instancesCount) {
  12191. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12192. }
  12193. else {
  12194. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12195. }
  12196. };
  12197. Engine.prototype.DrawMode = function (fillMode) {
  12198. switch (fillMode) {
  12199. // Triangle views
  12200. case BABYLON.Material.TriangleFillMode:
  12201. return this._gl.TRIANGLES;
  12202. case BABYLON.Material.PointFillMode:
  12203. return this._gl.POINTS;
  12204. case BABYLON.Material.WireFrameFillMode:
  12205. return this._gl.LINES;
  12206. // Draw modes
  12207. case BABYLON.Material.PointListDrawMode:
  12208. return this._gl.POINTS;
  12209. case BABYLON.Material.LineListDrawMode:
  12210. return this._gl.LINES;
  12211. case BABYLON.Material.LineLoopDrawMode:
  12212. return this._gl.LINE_LOOP;
  12213. case BABYLON.Material.LineStripDrawMode:
  12214. return this._gl.LINE_STRIP;
  12215. case BABYLON.Material.TriangleStripDrawMode:
  12216. return this._gl.TRIANGLE_STRIP;
  12217. case BABYLON.Material.TriangleFanDrawMode:
  12218. return this._gl.TRIANGLE_FAN;
  12219. default:
  12220. return this._gl.TRIANGLES;
  12221. }
  12222. };
  12223. // Shaders
  12224. Engine.prototype._releaseEffect = function (effect) {
  12225. if (this._compiledEffects[effect._key]) {
  12226. delete this._compiledEffects[effect._key];
  12227. this._deleteProgram(effect.getProgram());
  12228. }
  12229. };
  12230. Engine.prototype._deleteProgram = function (program) {
  12231. if (program) {
  12232. program.__SPECTOR_rebuildProgram = null;
  12233. if (program.transformFeedback) {
  12234. this.deleteTransformFeedback(program.transformFeedback);
  12235. program.transformFeedback = null;
  12236. }
  12237. this._gl.deleteProgram(program);
  12238. }
  12239. };
  12240. /**
  12241. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12242. * @param samplers An array of string used to represent textures
  12243. */
  12244. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12245. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12246. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12247. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12248. if (this._compiledEffects[name]) {
  12249. var compiledEffect = this._compiledEffects[name];
  12250. if (onCompiled && compiledEffect.isReady()) {
  12251. onCompiled(compiledEffect);
  12252. }
  12253. return compiledEffect;
  12254. }
  12255. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12256. effect._key = name;
  12257. this._compiledEffects[name] = effect;
  12258. return effect;
  12259. };
  12260. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12261. if (uniformsNames === void 0) { uniformsNames = []; }
  12262. if (samplers === void 0) { samplers = []; }
  12263. if (defines === void 0) { defines = ""; }
  12264. return this.createEffect({
  12265. vertex: "particles",
  12266. fragmentElement: fragmentName
  12267. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12268. };
  12269. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12270. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12271. context = context || this._gl;
  12272. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12273. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12274. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12275. };
  12276. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12277. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12278. context = context || this._gl;
  12279. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12280. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12281. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12282. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12283. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12284. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12285. return program;
  12286. };
  12287. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12288. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12289. var shaderProgram = context.createProgram();
  12290. if (!shaderProgram) {
  12291. throw new Error("Unable to create program");
  12292. }
  12293. context.attachShader(shaderProgram, vertexShader);
  12294. context.attachShader(shaderProgram, fragmentShader);
  12295. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12296. var transformFeedback = this.createTransformFeedback();
  12297. this.bindTransformFeedback(transformFeedback);
  12298. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12299. shaderProgram.transformFeedback = transformFeedback;
  12300. }
  12301. context.linkProgram(shaderProgram);
  12302. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12303. this.bindTransformFeedback(null);
  12304. }
  12305. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12306. if (!linked) {
  12307. context.validateProgram(shaderProgram);
  12308. var error = context.getProgramInfoLog(shaderProgram);
  12309. if (error) {
  12310. throw new Error(error);
  12311. }
  12312. }
  12313. context.deleteShader(vertexShader);
  12314. context.deleteShader(fragmentShader);
  12315. return shaderProgram;
  12316. };
  12317. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12318. var results = new Array();
  12319. for (var index = 0; index < uniformsNames.length; index++) {
  12320. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12321. }
  12322. return results;
  12323. };
  12324. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12325. var results = [];
  12326. for (var index = 0; index < attributesNames.length; index++) {
  12327. try {
  12328. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12329. }
  12330. catch (e) {
  12331. results.push(-1);
  12332. }
  12333. }
  12334. return results;
  12335. };
  12336. Engine.prototype.enableEffect = function (effect) {
  12337. if (!effect) {
  12338. return;
  12339. }
  12340. // Use program
  12341. this.bindSamplers(effect);
  12342. this._currentEffect = effect;
  12343. if (effect.onBind) {
  12344. effect.onBind(effect);
  12345. }
  12346. effect.onBindObservable.notifyObservers(effect);
  12347. };
  12348. Engine.prototype.setIntArray = function (uniform, array) {
  12349. if (!uniform)
  12350. return;
  12351. this._gl.uniform1iv(uniform, array);
  12352. };
  12353. Engine.prototype.setIntArray2 = function (uniform, array) {
  12354. if (!uniform || array.length % 2 !== 0)
  12355. return;
  12356. this._gl.uniform2iv(uniform, array);
  12357. };
  12358. Engine.prototype.setIntArray3 = function (uniform, array) {
  12359. if (!uniform || array.length % 3 !== 0)
  12360. return;
  12361. this._gl.uniform3iv(uniform, array);
  12362. };
  12363. Engine.prototype.setIntArray4 = function (uniform, array) {
  12364. if (!uniform || array.length % 4 !== 0)
  12365. return;
  12366. this._gl.uniform4iv(uniform, array);
  12367. };
  12368. Engine.prototype.setFloatArray = function (uniform, array) {
  12369. if (!uniform)
  12370. return;
  12371. this._gl.uniform1fv(uniform, array);
  12372. };
  12373. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12374. if (!uniform || array.length % 2 !== 0)
  12375. return;
  12376. this._gl.uniform2fv(uniform, array);
  12377. };
  12378. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12379. if (!uniform || array.length % 3 !== 0)
  12380. return;
  12381. this._gl.uniform3fv(uniform, array);
  12382. };
  12383. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12384. if (!uniform || array.length % 4 !== 0)
  12385. return;
  12386. this._gl.uniform4fv(uniform, array);
  12387. };
  12388. Engine.prototype.setArray = function (uniform, array) {
  12389. if (!uniform)
  12390. return;
  12391. this._gl.uniform1fv(uniform, array);
  12392. };
  12393. Engine.prototype.setArray2 = function (uniform, array) {
  12394. if (!uniform || array.length % 2 !== 0)
  12395. return;
  12396. this._gl.uniform2fv(uniform, array);
  12397. };
  12398. Engine.prototype.setArray3 = function (uniform, array) {
  12399. if (!uniform || array.length % 3 !== 0)
  12400. return;
  12401. this._gl.uniform3fv(uniform, array);
  12402. };
  12403. Engine.prototype.setArray4 = function (uniform, array) {
  12404. if (!uniform || array.length % 4 !== 0)
  12405. return;
  12406. this._gl.uniform4fv(uniform, array);
  12407. };
  12408. Engine.prototype.setMatrices = function (uniform, matrices) {
  12409. if (!uniform)
  12410. return;
  12411. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12412. };
  12413. Engine.prototype.setMatrix = function (uniform, matrix) {
  12414. if (!uniform)
  12415. return;
  12416. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12417. };
  12418. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12419. if (!uniform)
  12420. return;
  12421. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12422. };
  12423. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12424. if (!uniform)
  12425. return;
  12426. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12427. };
  12428. Engine.prototype.setInt = function (uniform, value) {
  12429. if (!uniform)
  12430. return;
  12431. this._gl.uniform1i(uniform, value);
  12432. };
  12433. Engine.prototype.setFloat = function (uniform, value) {
  12434. if (!uniform)
  12435. return;
  12436. this._gl.uniform1f(uniform, value);
  12437. };
  12438. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12439. if (!uniform)
  12440. return;
  12441. this._gl.uniform2f(uniform, x, y);
  12442. };
  12443. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12444. if (!uniform)
  12445. return;
  12446. this._gl.uniform3f(uniform, x, y, z);
  12447. };
  12448. Engine.prototype.setBool = function (uniform, bool) {
  12449. if (!uniform)
  12450. return;
  12451. this._gl.uniform1i(uniform, bool);
  12452. };
  12453. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12454. if (!uniform)
  12455. return;
  12456. this._gl.uniform4f(uniform, x, y, z, w);
  12457. };
  12458. Engine.prototype.setColor3 = function (uniform, color3) {
  12459. if (!uniform)
  12460. return;
  12461. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12462. };
  12463. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12464. if (!uniform)
  12465. return;
  12466. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12467. };
  12468. // States
  12469. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12470. if (zOffset === void 0) { zOffset = 0; }
  12471. if (reverseSide === void 0) { reverseSide = false; }
  12472. // Culling
  12473. if (this._depthCullingState.cull !== culling || force) {
  12474. this._depthCullingState.cull = culling;
  12475. }
  12476. // Cull face
  12477. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12478. if (this._depthCullingState.cullFace !== cullFace || force) {
  12479. this._depthCullingState.cullFace = cullFace;
  12480. }
  12481. // Z offset
  12482. this.setZOffset(zOffset);
  12483. // Front face
  12484. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12485. if (this._depthCullingState.frontFace !== frontFace || force) {
  12486. this._depthCullingState.frontFace = frontFace;
  12487. }
  12488. };
  12489. Engine.prototype.setZOffset = function (value) {
  12490. this._depthCullingState.zOffset = value;
  12491. };
  12492. Engine.prototype.getZOffset = function () {
  12493. return this._depthCullingState.zOffset;
  12494. };
  12495. Engine.prototype.setDepthBuffer = function (enable) {
  12496. this._depthCullingState.depthTest = enable;
  12497. };
  12498. Engine.prototype.getDepthWrite = function () {
  12499. return this._depthCullingState.depthMask;
  12500. };
  12501. Engine.prototype.setDepthWrite = function (enable) {
  12502. this._depthCullingState.depthMask = enable;
  12503. };
  12504. Engine.prototype.setColorWrite = function (enable) {
  12505. this._gl.colorMask(enable, enable, enable, enable);
  12506. this._colorWrite = enable;
  12507. };
  12508. Engine.prototype.getColorWrite = function () {
  12509. return this._colorWrite;
  12510. };
  12511. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12512. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12513. };
  12514. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12515. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12516. if (this._alphaMode === mode) {
  12517. return;
  12518. }
  12519. switch (mode) {
  12520. case Engine.ALPHA_DISABLE:
  12521. this._alphaState.alphaBlend = false;
  12522. break;
  12523. case Engine.ALPHA_PREMULTIPLIED:
  12524. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12525. this._alphaState.alphaBlend = true;
  12526. break;
  12527. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12528. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12529. this._alphaState.alphaBlend = true;
  12530. break;
  12531. case Engine.ALPHA_COMBINE:
  12532. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12533. this._alphaState.alphaBlend = true;
  12534. break;
  12535. case Engine.ALPHA_ONEONE:
  12536. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12537. this._alphaState.alphaBlend = true;
  12538. break;
  12539. case Engine.ALPHA_ADD:
  12540. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12541. this._alphaState.alphaBlend = true;
  12542. break;
  12543. case Engine.ALPHA_SUBTRACT:
  12544. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12545. this._alphaState.alphaBlend = true;
  12546. break;
  12547. case Engine.ALPHA_MULTIPLY:
  12548. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12549. this._alphaState.alphaBlend = true;
  12550. break;
  12551. case Engine.ALPHA_MAXIMIZED:
  12552. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12553. this._alphaState.alphaBlend = true;
  12554. break;
  12555. case Engine.ALPHA_INTERPOLATE:
  12556. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12557. this._alphaState.alphaBlend = true;
  12558. break;
  12559. case Engine.ALPHA_SCREENMODE:
  12560. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12561. this._alphaState.alphaBlend = true;
  12562. break;
  12563. }
  12564. if (!noDepthWriteChange) {
  12565. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12566. }
  12567. this._alphaMode = mode;
  12568. };
  12569. Engine.prototype.getAlphaMode = function () {
  12570. return this._alphaMode;
  12571. };
  12572. // Textures
  12573. Engine.prototype.wipeCaches = function (bruteForce) {
  12574. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12575. return;
  12576. }
  12577. this._currentEffect = null;
  12578. // 6/8/2017: deltakosh: Should not be required anymore.
  12579. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12580. if (bruteForce) {
  12581. this.resetTextureCache();
  12582. this._currentProgram = null;
  12583. this._stencilState.reset();
  12584. this._depthCullingState.reset();
  12585. this.setDepthFunctionToLessOrEqual();
  12586. this._alphaState.reset();
  12587. }
  12588. this._resetVertexBufferBinding();
  12589. this._cachedIndexBuffer = null;
  12590. this._cachedEffectForVertexBuffers = null;
  12591. this._unbindVertexArrayObject();
  12592. this.bindIndexBuffer(null);
  12593. };
  12594. /**
  12595. * Set the compressed texture format to use, based on the formats you have, and the formats
  12596. * supported by the hardware / browser.
  12597. *
  12598. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12599. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12600. * to API arguments needed to compressed textures. This puts the burden on the container
  12601. * generator to house the arcane code for determining these for current & future formats.
  12602. *
  12603. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12604. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12605. *
  12606. * Note: The result of this call is not taken into account when a texture is base64.
  12607. *
  12608. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12609. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12610. *
  12611. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12612. * @returns The extension selected.
  12613. */
  12614. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12615. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12616. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12617. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12618. return this._textureFormatInUse = this._texturesSupported[i];
  12619. }
  12620. }
  12621. }
  12622. // actively set format to nothing, to allow this to be called more than once
  12623. // and possibly fail the 2nd time
  12624. this._textureFormatInUse = null;
  12625. return null;
  12626. };
  12627. Engine.prototype._createTexture = function () {
  12628. var texture = this._gl.createTexture();
  12629. if (!texture) {
  12630. throw new Error("Unable to create texture");
  12631. }
  12632. return texture;
  12633. };
  12634. /**
  12635. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12636. * @param {string} urlArg- This contains one of the following:
  12637. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12638. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12639. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12640. *
  12641. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12642. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12643. * @param {Scene} scene- Needed for loading to the correct scene.
  12644. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12645. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12646. * @param {callback} onError- Optional callback to be called upon failure.
  12647. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12648. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12649. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12650. *
  12651. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12652. */
  12653. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12654. var _this = this;
  12655. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12656. if (onLoad === void 0) { onLoad = null; }
  12657. if (onError === void 0) { onError = null; }
  12658. if (buffer === void 0) { buffer = null; }
  12659. if (fallBack === void 0) { fallBack = null; }
  12660. if (format === void 0) { format = null; }
  12661. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12662. var fromData = url.substr(0, 5) === "data:";
  12663. var fromBlob = url.substr(0, 5) === "blob:";
  12664. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12665. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12666. // establish the file extension, if possible
  12667. var lastDot = url.lastIndexOf('.');
  12668. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12669. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12670. var isTGA = (extension.indexOf(".tga") === 0);
  12671. // determine if a ktx file should be substituted
  12672. var isKTX = false;
  12673. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12674. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12675. isKTX = true;
  12676. }
  12677. if (scene) {
  12678. scene._addPendingData(texture);
  12679. }
  12680. texture.url = url;
  12681. texture.generateMipMaps = !noMipmap;
  12682. texture.samplingMode = samplingMode;
  12683. texture.invertY = invertY;
  12684. if (!this._doNotHandleContextLost) {
  12685. // Keep a link to the buffer only if we plan to handle context lost
  12686. texture._buffer = buffer;
  12687. }
  12688. var onLoadObserver = null;
  12689. if (onLoad && !fallBack) {
  12690. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12691. }
  12692. if (!fallBack)
  12693. this._internalTexturesCache.push(texture);
  12694. var onerror = function (message, exception) {
  12695. if (scene) {
  12696. scene._removePendingData(texture);
  12697. }
  12698. if (onLoadObserver) {
  12699. texture.onLoadedObservable.remove(onLoadObserver);
  12700. }
  12701. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12702. if (isKTX) {
  12703. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12704. }
  12705. else if (BABYLON.Tools.UseFallbackTexture) {
  12706. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12707. }
  12708. if (onError) {
  12709. onError(message || "Unknown error", exception);
  12710. }
  12711. };
  12712. var callback = null;
  12713. // processing for non-image formats
  12714. if (isKTX || isTGA || isDDS) {
  12715. if (isKTX) {
  12716. callback = function (data) {
  12717. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12718. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12719. ktx.uploadLevels(_this._gl, !noMipmap);
  12720. return false;
  12721. }, samplingMode);
  12722. };
  12723. }
  12724. else if (isTGA) {
  12725. callback = function (arrayBuffer) {
  12726. var data = new Uint8Array(arrayBuffer);
  12727. var header = BABYLON.TGATools.GetTGAHeader(data);
  12728. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12729. BABYLON.TGATools.UploadContent(_this._gl, data);
  12730. return false;
  12731. }, samplingMode);
  12732. };
  12733. }
  12734. else if (isDDS) {
  12735. callback = function (data) {
  12736. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12737. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12738. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12739. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12740. return false;
  12741. }, samplingMode);
  12742. };
  12743. }
  12744. if (!buffer) {
  12745. this._loadFile(url, function (data) {
  12746. if (callback) {
  12747. callback(data);
  12748. }
  12749. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12750. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12751. });
  12752. }
  12753. else {
  12754. if (callback) {
  12755. callback(buffer);
  12756. }
  12757. }
  12758. // image format processing
  12759. }
  12760. else {
  12761. var onload = function (img) {
  12762. if (fromBlob && !_this._doNotHandleContextLost) {
  12763. // We need to store the image if we need to rebuild the texture
  12764. // in case of a webgl context lost
  12765. texture._buffer = img;
  12766. }
  12767. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12768. var gl = _this._gl;
  12769. var isPot = (img.width === potWidth && img.height === potHeight);
  12770. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12771. if (isPot) {
  12772. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12773. return false;
  12774. }
  12775. // Using shaders to rescale because canvas.drawImage is lossy
  12776. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12777. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12778. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12780. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12782. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12783. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12784. _this._releaseTexture(source);
  12785. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12786. continuationCallback();
  12787. });
  12788. return true;
  12789. }, samplingMode);
  12790. };
  12791. if (!fromData || isBase64)
  12792. if (buffer instanceof HTMLImageElement) {
  12793. onload(buffer);
  12794. }
  12795. else {
  12796. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12797. }
  12798. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12799. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12800. else
  12801. onload(buffer);
  12802. }
  12803. return texture;
  12804. };
  12805. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12806. var _this = this;
  12807. var rtt = this.createRenderTargetTexture({
  12808. width: destination.width,
  12809. height: destination.height,
  12810. }, {
  12811. generateMipMaps: false,
  12812. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12813. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12814. generateDepthBuffer: false,
  12815. generateStencilBuffer: false
  12816. });
  12817. if (!this._rescalePostProcess) {
  12818. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12819. }
  12820. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12821. _this._rescalePostProcess.onApply = function (effect) {
  12822. effect._bindTexture("textureSampler", source);
  12823. };
  12824. var hostingScene = scene;
  12825. if (!hostingScene) {
  12826. hostingScene = _this.scenes[_this.scenes.length - 1];
  12827. }
  12828. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12829. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12830. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12831. _this.unBindFramebuffer(rtt);
  12832. _this._releaseTexture(rtt);
  12833. if (onComplete) {
  12834. onComplete();
  12835. }
  12836. });
  12837. };
  12838. Engine.prototype._getInternalFormat = function (format) {
  12839. var internalFormat = this._gl.RGBA;
  12840. switch (format) {
  12841. case Engine.TEXTUREFORMAT_ALPHA:
  12842. internalFormat = this._gl.ALPHA;
  12843. break;
  12844. case Engine.TEXTUREFORMAT_LUMINANCE:
  12845. internalFormat = this._gl.LUMINANCE;
  12846. break;
  12847. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12848. internalFormat = this._gl.LUMINANCE_ALPHA;
  12849. break;
  12850. case Engine.TEXTUREFORMAT_RGB:
  12851. internalFormat = this._gl.RGB;
  12852. break;
  12853. case Engine.TEXTUREFORMAT_RGBA:
  12854. internalFormat = this._gl.RGBA;
  12855. break;
  12856. }
  12857. return internalFormat;
  12858. };
  12859. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12860. if (compression === void 0) { compression = null; }
  12861. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12862. if (!texture) {
  12863. return;
  12864. }
  12865. var internalFormat = this._getInternalFormat(format);
  12866. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12867. var textureType = this._getWebGLTextureType(type);
  12868. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12869. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12870. if (!this._doNotHandleContextLost) {
  12871. texture._bufferView = data;
  12872. texture.format = format;
  12873. texture.type = type;
  12874. texture.invertY = invertY;
  12875. texture._compression = compression;
  12876. }
  12877. if (texture.width % 4 !== 0) {
  12878. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12879. }
  12880. if (compression && data) {
  12881. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12882. }
  12883. else {
  12884. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12885. }
  12886. if (texture.generateMipMaps) {
  12887. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12888. }
  12889. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12890. // this.resetTextureCache();
  12891. texture.isReady = true;
  12892. };
  12893. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12894. if (compression === void 0) { compression = null; }
  12895. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12896. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12897. texture.baseWidth = width;
  12898. texture.baseHeight = height;
  12899. texture.width = width;
  12900. texture.height = height;
  12901. texture.format = format;
  12902. texture.generateMipMaps = generateMipMaps;
  12903. texture.samplingMode = samplingMode;
  12904. texture.invertY = invertY;
  12905. texture._compression = compression;
  12906. texture.type = type;
  12907. if (!this._doNotHandleContextLost) {
  12908. texture._bufferView = data;
  12909. }
  12910. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12911. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12912. // Filters
  12913. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12914. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12915. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12916. if (generateMipMaps) {
  12917. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12918. }
  12919. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12920. this._internalTexturesCache.push(texture);
  12921. return texture;
  12922. };
  12923. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12924. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12925. texture.baseWidth = width;
  12926. texture.baseHeight = height;
  12927. if (generateMipMaps) {
  12928. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12929. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12930. }
  12931. // this.resetTextureCache();
  12932. texture.width = width;
  12933. texture.height = height;
  12934. texture.isReady = false;
  12935. texture.generateMipMaps = generateMipMaps;
  12936. texture.samplingMode = samplingMode;
  12937. this.updateTextureSamplingMode(samplingMode, texture);
  12938. this._internalTexturesCache.push(texture);
  12939. return texture;
  12940. };
  12941. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12942. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12943. if (texture.isCube) {
  12944. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12945. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12946. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12947. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12948. }
  12949. else if (texture.is3D) {
  12950. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12951. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12952. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12953. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12954. }
  12955. else {
  12956. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12957. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12958. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12959. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12960. }
  12961. texture.samplingMode = samplingMode;
  12962. };
  12963. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12964. if (premulAlpha === void 0) { premulAlpha = false; }
  12965. if (!texture) {
  12966. return;
  12967. }
  12968. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12969. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12970. if (premulAlpha) {
  12971. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12972. }
  12973. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12974. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12975. if (texture.generateMipMaps) {
  12976. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12977. }
  12978. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12979. if (premulAlpha) {
  12980. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12981. }
  12982. texture.isReady = true;
  12983. };
  12984. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12985. if (!texture || texture._isDisabled) {
  12986. return;
  12987. }
  12988. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12989. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12990. try {
  12991. // Testing video texture support
  12992. if (this._videoTextureSupported === undefined) {
  12993. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12994. if (this._gl.getError() !== 0) {
  12995. this._videoTextureSupported = false;
  12996. }
  12997. else {
  12998. this._videoTextureSupported = true;
  12999. }
  13000. }
  13001. // Copy video through the current working canvas if video texture is not supported
  13002. if (!this._videoTextureSupported) {
  13003. if (!texture._workingCanvas) {
  13004. texture._workingCanvas = document.createElement("canvas");
  13005. var context = texture._workingCanvas.getContext("2d");
  13006. if (!context) {
  13007. throw new Error("Unable to get 2d context");
  13008. }
  13009. texture._workingContext = context;
  13010. texture._workingCanvas.width = texture.width;
  13011. texture._workingCanvas.height = texture.height;
  13012. }
  13013. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13014. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13015. }
  13016. else {
  13017. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13018. }
  13019. if (texture.generateMipMaps) {
  13020. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13021. }
  13022. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13023. // this.resetTextureCache();
  13024. texture.isReady = true;
  13025. }
  13026. catch (ex) {
  13027. // Something unexpected
  13028. // Let's disable the texture
  13029. texture._isDisabled = true;
  13030. }
  13031. };
  13032. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13033. var fullOptions = new RenderTargetCreationOptions();
  13034. if (options !== undefined && typeof options === "object") {
  13035. fullOptions.generateMipMaps = options.generateMipMaps;
  13036. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13037. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13038. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13039. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13040. }
  13041. else {
  13042. fullOptions.generateMipMaps = options;
  13043. fullOptions.generateDepthBuffer = true;
  13044. fullOptions.generateStencilBuffer = false;
  13045. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13046. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13047. }
  13048. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13049. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13050. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13051. }
  13052. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13053. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13054. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13055. }
  13056. var gl = this._gl;
  13057. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13058. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13059. var width = size.width || size;
  13060. var height = size.height || size;
  13061. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13062. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13063. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13064. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13065. }
  13066. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13067. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13068. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13069. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13070. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13071. // Create the framebuffer
  13072. var framebuffer = gl.createFramebuffer();
  13073. this.bindUnboundFramebuffer(framebuffer);
  13074. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13075. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13076. if (fullOptions.generateMipMaps) {
  13077. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13078. }
  13079. // Unbind
  13080. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13081. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13082. this.bindUnboundFramebuffer(null);
  13083. texture._framebuffer = framebuffer;
  13084. texture.baseWidth = width;
  13085. texture.baseHeight = height;
  13086. texture.width = width;
  13087. texture.height = height;
  13088. texture.isReady = true;
  13089. texture.samples = 1;
  13090. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13091. texture.samplingMode = fullOptions.samplingMode;
  13092. texture.type = fullOptions.type;
  13093. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13094. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13095. // this.resetTextureCache();
  13096. this._internalTexturesCache.push(texture);
  13097. return texture;
  13098. };
  13099. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13100. var generateMipMaps = false;
  13101. var generateDepthBuffer = true;
  13102. var generateStencilBuffer = false;
  13103. var generateDepthTexture = false;
  13104. var textureCount = 1;
  13105. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13106. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13107. var types = [], samplingModes = [];
  13108. if (options !== undefined) {
  13109. generateMipMaps = options.generateMipMaps;
  13110. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13111. generateStencilBuffer = options.generateStencilBuffer;
  13112. generateDepthTexture = options.generateDepthTexture;
  13113. textureCount = options.textureCount || 1;
  13114. if (options.types) {
  13115. types = options.types;
  13116. }
  13117. if (options.samplingModes) {
  13118. samplingModes = options.samplingModes;
  13119. }
  13120. }
  13121. var gl = this._gl;
  13122. // Create the framebuffer
  13123. var framebuffer = gl.createFramebuffer();
  13124. this.bindUnboundFramebuffer(framebuffer);
  13125. var width = size.width || size;
  13126. var height = size.height || size;
  13127. var textures = [];
  13128. var attachments = [];
  13129. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13130. for (var i = 0; i < textureCount; i++) {
  13131. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13132. var type = types[i] || defaultType;
  13133. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13134. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13135. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13136. }
  13137. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13138. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13139. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13140. }
  13141. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13142. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13143. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13144. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13145. }
  13146. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13147. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13148. textures.push(texture);
  13149. attachments.push(attachment);
  13150. gl.activeTexture(gl["TEXTURE" + i]);
  13151. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13152. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13153. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13154. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13155. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13156. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13157. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13158. if (generateMipMaps) {
  13159. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13160. }
  13161. // Unbind
  13162. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13163. texture._framebuffer = framebuffer;
  13164. texture._depthStencilBuffer = depthStencilBuffer;
  13165. texture.baseWidth = width;
  13166. texture.baseHeight = height;
  13167. texture.width = width;
  13168. texture.height = height;
  13169. texture.isReady = true;
  13170. texture.samples = 1;
  13171. texture.generateMipMaps = generateMipMaps;
  13172. texture.samplingMode = samplingMode;
  13173. texture.type = type;
  13174. texture._generateDepthBuffer = generateDepthBuffer;
  13175. texture._generateStencilBuffer = generateStencilBuffer;
  13176. texture._attachments = attachments;
  13177. this._internalTexturesCache.push(texture);
  13178. }
  13179. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13180. // Depth texture
  13181. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13182. gl.activeTexture(gl.TEXTURE0);
  13183. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13184. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13185. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13186. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13187. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13188. 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);
  13189. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13190. depthTexture._framebuffer = framebuffer;
  13191. depthTexture.baseWidth = width;
  13192. depthTexture.baseHeight = height;
  13193. depthTexture.width = width;
  13194. depthTexture.height = height;
  13195. depthTexture.isReady = true;
  13196. depthTexture.samples = 1;
  13197. depthTexture.generateMipMaps = generateMipMaps;
  13198. depthTexture.samplingMode = gl.NEAREST;
  13199. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13200. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13201. textures.push(depthTexture);
  13202. this._internalTexturesCache.push(depthTexture);
  13203. }
  13204. gl.drawBuffers(attachments);
  13205. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13206. this.bindUnboundFramebuffer(null);
  13207. this.resetTextureCache();
  13208. return textures;
  13209. };
  13210. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13211. if (samples === void 0) { samples = 1; }
  13212. var depthStencilBuffer = null;
  13213. var gl = this._gl;
  13214. // Create the depth/stencil buffer
  13215. if (generateStencilBuffer) {
  13216. depthStencilBuffer = gl.createRenderbuffer();
  13217. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13218. if (samples > 1) {
  13219. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13220. }
  13221. else {
  13222. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13223. }
  13224. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13225. }
  13226. else if (generateDepthBuffer) {
  13227. depthStencilBuffer = gl.createRenderbuffer();
  13228. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13229. if (samples > 1) {
  13230. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13231. }
  13232. else {
  13233. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13234. }
  13235. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13236. }
  13237. return depthStencilBuffer;
  13238. };
  13239. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13240. if (this.webGLVersion < 2 || !texture) {
  13241. return 1;
  13242. }
  13243. if (texture.samples === samples) {
  13244. return samples;
  13245. }
  13246. var gl = this._gl;
  13247. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13248. // Dispose previous render buffers
  13249. if (texture._depthStencilBuffer) {
  13250. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13251. texture._depthStencilBuffer = null;
  13252. }
  13253. if (texture._MSAAFramebuffer) {
  13254. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13255. texture._MSAAFramebuffer = null;
  13256. }
  13257. if (texture._MSAARenderBuffer) {
  13258. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13259. texture._MSAARenderBuffer = null;
  13260. }
  13261. if (samples > 1) {
  13262. var framebuffer = gl.createFramebuffer();
  13263. if (!framebuffer) {
  13264. throw new Error("Unable to create multi sampled framebuffer");
  13265. }
  13266. texture._MSAAFramebuffer = framebuffer;
  13267. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13268. var colorRenderbuffer = gl.createRenderbuffer();
  13269. if (!colorRenderbuffer) {
  13270. throw new Error("Unable to create multi sampled framebuffer");
  13271. }
  13272. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13273. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13274. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13275. texture._MSAARenderBuffer = colorRenderbuffer;
  13276. }
  13277. else {
  13278. this.bindUnboundFramebuffer(texture._framebuffer);
  13279. }
  13280. texture.samples = samples;
  13281. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13282. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13283. this.bindUnboundFramebuffer(null);
  13284. return samples;
  13285. };
  13286. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13287. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13288. return 1;
  13289. }
  13290. if (textures[0].samples === samples) {
  13291. return samples;
  13292. }
  13293. var gl = this._gl;
  13294. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13295. // Dispose previous render buffers
  13296. if (textures[0]._depthStencilBuffer) {
  13297. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13298. textures[0]._depthStencilBuffer = null;
  13299. }
  13300. if (textures[0]._MSAAFramebuffer) {
  13301. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13302. textures[0]._MSAAFramebuffer = null;
  13303. }
  13304. for (var i = 0; i < textures.length; i++) {
  13305. if (textures[i]._MSAARenderBuffer) {
  13306. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13307. textures[i]._MSAARenderBuffer = null;
  13308. }
  13309. }
  13310. if (samples > 1) {
  13311. var framebuffer = gl.createFramebuffer();
  13312. if (!framebuffer) {
  13313. throw new Error("Unable to create multi sampled framebuffer");
  13314. }
  13315. this.bindUnboundFramebuffer(framebuffer);
  13316. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13317. var attachments = [];
  13318. for (var i = 0; i < textures.length; i++) {
  13319. var texture = textures[i];
  13320. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13321. var colorRenderbuffer = gl.createRenderbuffer();
  13322. if (!colorRenderbuffer) {
  13323. throw new Error("Unable to create multi sampled framebuffer");
  13324. }
  13325. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13326. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13327. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13328. texture._MSAAFramebuffer = framebuffer;
  13329. texture._MSAARenderBuffer = colorRenderbuffer;
  13330. texture.samples = samples;
  13331. texture._depthStencilBuffer = depthStencilBuffer;
  13332. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13333. attachments.push(attachment);
  13334. }
  13335. gl.drawBuffers(attachments);
  13336. }
  13337. else {
  13338. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13339. }
  13340. this.bindUnboundFramebuffer(null);
  13341. return samples;
  13342. };
  13343. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13344. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13345. };
  13346. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13347. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13348. };
  13349. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13350. var gl = this._gl;
  13351. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13352. var generateMipMaps = true;
  13353. var generateDepthBuffer = true;
  13354. var generateStencilBuffer = false;
  13355. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13356. if (options !== undefined) {
  13357. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  13358. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13359. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  13360. if (options.samplingMode !== undefined) {
  13361. samplingMode = options.samplingMode;
  13362. }
  13363. }
  13364. texture.isCube = true;
  13365. texture.generateMipMaps = generateMipMaps;
  13366. texture.samples = 1;
  13367. texture.samplingMode = samplingMode;
  13368. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13369. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13370. for (var face = 0; face < 6; face++) {
  13371. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  13372. }
  13373. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13374. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13375. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13376. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13377. // Create the framebuffer
  13378. var framebuffer = gl.createFramebuffer();
  13379. this.bindUnboundFramebuffer(framebuffer);
  13380. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  13381. // Mipmaps
  13382. if (texture.generateMipMaps) {
  13383. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13384. }
  13385. // Unbind
  13386. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13387. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13388. this.bindUnboundFramebuffer(null);
  13389. texture._framebuffer = framebuffer;
  13390. texture.width = size;
  13391. texture.height = size;
  13392. texture.isReady = true;
  13393. //this.resetTextureCache();
  13394. this._internalTexturesCache.push(texture);
  13395. return texture;
  13396. };
  13397. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13398. var _this = this;
  13399. if (onLoad === void 0) { onLoad = null; }
  13400. if (onError === void 0) { onError = null; }
  13401. if (forcedExtension === void 0) { forcedExtension = null; }
  13402. var callback = function (loadData) {
  13403. if (!loadData) {
  13404. if (onLoad) {
  13405. onLoad(null);
  13406. }
  13407. return;
  13408. }
  13409. var texture = loadData.texture;
  13410. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13411. texture._lodGenerationScale = scale;
  13412. texture._lodGenerationOffset = offset;
  13413. if (_this._caps.textureLOD) {
  13414. // Do not add extra process if texture lod is supported.
  13415. if (onLoad) {
  13416. onLoad(texture);
  13417. }
  13418. return;
  13419. }
  13420. var mipSlices = 3;
  13421. var gl = _this._gl;
  13422. var width = loadData.width;
  13423. if (!width) {
  13424. return;
  13425. }
  13426. var textures = [];
  13427. for (var i = 0; i < mipSlices; i++) {
  13428. //compute LOD from even spacing in smoothness (matching shader calculation)
  13429. var smoothness = i / (mipSlices - 1);
  13430. var roughness = 1 - smoothness;
  13431. var minLODIndex = offset; // roughness = 0
  13432. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13433. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13434. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13435. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13436. glTextureFromLod.isCube = true;
  13437. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13438. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13439. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13440. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13441. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13442. if (loadData.isDDS) {
  13443. var info = loadData.info;
  13444. var data = loadData.data;
  13445. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13446. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13447. }
  13448. else {
  13449. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13450. }
  13451. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13452. // Wrap in a base texture for easy binding.
  13453. var lodTexture = new BABYLON.BaseTexture(scene);
  13454. lodTexture.isCube = true;
  13455. lodTexture._texture = glTextureFromLod;
  13456. glTextureFromLod.isReady = true;
  13457. textures.push(lodTexture);
  13458. }
  13459. texture._lodTextureHigh = textures[2];
  13460. texture._lodTextureMid = textures[1];
  13461. texture._lodTextureLow = textures[0];
  13462. if (onLoad) {
  13463. onLoad(texture);
  13464. }
  13465. };
  13466. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13467. };
  13468. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13469. var _this = this;
  13470. if (onLoad === void 0) { onLoad = null; }
  13471. if (onError === void 0) { onError = null; }
  13472. if (forcedExtension === void 0) { forcedExtension = null; }
  13473. var gl = this._gl;
  13474. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13475. texture.isCube = true;
  13476. texture.url = rootUrl;
  13477. texture.generateMipMaps = !noMipmap;
  13478. if (!this._doNotHandleContextLost) {
  13479. texture._extension = forcedExtension;
  13480. texture._files = files;
  13481. }
  13482. var isKTX = false;
  13483. var isDDS = false;
  13484. var lastDot = rootUrl.lastIndexOf('.');
  13485. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13486. if (this._textureFormatInUse) {
  13487. extension = this._textureFormatInUse;
  13488. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13489. isKTX = true;
  13490. }
  13491. else {
  13492. isDDS = (extension === ".dds");
  13493. }
  13494. var onerror = function (request, exception) {
  13495. if (onError && request) {
  13496. onError(request.status + " " + request.statusText, exception);
  13497. }
  13498. };
  13499. if (isKTX) {
  13500. this._loadFile(rootUrl, function (data) {
  13501. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13502. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13503. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13504. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13505. ktx.uploadLevels(_this._gl, !noMipmap);
  13506. _this.setCubeMapTextureParams(gl, loadMipmap);
  13507. texture.width = ktx.pixelWidth;
  13508. texture.height = ktx.pixelHeight;
  13509. texture.isReady = true;
  13510. }, undefined, undefined, true, onerror);
  13511. }
  13512. else if (isDDS) {
  13513. if (files && files.length === 6) {
  13514. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  13515. var info;
  13516. var loadMipmap = false;
  13517. var width = 0;
  13518. for (var index = 0; index < imgs.length; index++) {
  13519. var data = imgs[index];
  13520. info = BABYLON.DDSTools.GetDDSInfo(data);
  13521. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13522. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13523. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13524. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13525. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13526. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13527. }
  13528. texture.width = info.width;
  13529. texture.height = info.height;
  13530. texture.type = info.textureType;
  13531. width = info.width;
  13532. }
  13533. _this.setCubeMapTextureParams(gl, loadMipmap);
  13534. texture.isReady = true;
  13535. if (onLoad) {
  13536. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13537. }
  13538. }, files, onError);
  13539. }
  13540. else {
  13541. this._loadFile(rootUrl, function (data) {
  13542. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13543. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13544. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13545. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13546. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13547. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13548. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13549. }
  13550. _this.setCubeMapTextureParams(gl, loadMipmap);
  13551. texture.width = info.width;
  13552. texture.height = info.height;
  13553. texture.isReady = true;
  13554. texture.type = info.textureType;
  13555. if (onLoad) {
  13556. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13557. }
  13558. }, undefined, undefined, true, onerror);
  13559. }
  13560. }
  13561. else {
  13562. if (!files) {
  13563. throw new Error("Cannot load cubemap because files were not defined");
  13564. }
  13565. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13566. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13567. var height = width;
  13568. _this._prepareWorkingCanvas();
  13569. if (!_this._workingCanvas || !_this._workingContext) {
  13570. return;
  13571. }
  13572. _this._workingCanvas.width = width;
  13573. _this._workingCanvas.height = height;
  13574. var faces = [
  13575. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13576. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13577. ];
  13578. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13579. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13580. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13581. for (var index = 0; index < faces.length; index++) {
  13582. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13583. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13584. }
  13585. if (!noMipmap) {
  13586. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13587. }
  13588. _this.setCubeMapTextureParams(gl, !noMipmap);
  13589. texture.width = width;
  13590. texture.height = height;
  13591. texture.isReady = true;
  13592. if (format) {
  13593. texture.format = format;
  13594. }
  13595. texture.onLoadedObservable.notifyObservers(texture);
  13596. texture.onLoadedObservable.clear();
  13597. if (onLoad) {
  13598. onLoad();
  13599. }
  13600. }, files, onError);
  13601. }
  13602. this._internalTexturesCache.push(texture);
  13603. return texture;
  13604. };
  13605. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13606. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13607. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13608. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13609. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13610. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13611. // this.resetTextureCache();
  13612. };
  13613. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13614. if (compression === void 0) { compression = null; }
  13615. if (level === void 0) { level = 0; }
  13616. texture._bufferViewArray = data;
  13617. texture.format = format;
  13618. texture.type = type;
  13619. texture.invertY = invertY;
  13620. texture._compression = compression;
  13621. var gl = this._gl;
  13622. var textureType = this._getWebGLTextureType(type);
  13623. var internalFormat = this._getInternalFormat(format);
  13624. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13625. var needConversion = false;
  13626. if (internalFormat === gl.RGB) {
  13627. internalFormat = gl.RGBA;
  13628. needConversion = true;
  13629. }
  13630. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13631. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13632. if (texture.width % 4 !== 0) {
  13633. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13634. }
  13635. // Data are known to be in +X +Y +Z -X -Y -Z
  13636. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13637. var faceData = data[faceIndex];
  13638. if (compression) {
  13639. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13640. }
  13641. else {
  13642. if (needConversion) {
  13643. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13644. }
  13645. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13646. }
  13647. }
  13648. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13649. if (isPot && texture.generateMipMaps && level === 0) {
  13650. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13651. }
  13652. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13653. // this.resetTextureCache();
  13654. texture.isReady = true;
  13655. };
  13656. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13657. if (compression === void 0) { compression = null; }
  13658. var gl = this._gl;
  13659. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13660. texture.isCube = true;
  13661. texture.generateMipMaps = generateMipMaps;
  13662. texture.format = format;
  13663. texture.type = type;
  13664. if (!this._doNotHandleContextLost) {
  13665. texture._bufferViewArray = data;
  13666. }
  13667. var textureType = this._getWebGLTextureType(type);
  13668. var internalFormat = this._getInternalFormat(format);
  13669. if (internalFormat === gl.RGB) {
  13670. internalFormat = gl.RGBA;
  13671. }
  13672. var width = size;
  13673. var height = width;
  13674. texture.width = width;
  13675. texture.height = height;
  13676. // Double check on POT to generate Mips.
  13677. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13678. if (!isPot) {
  13679. generateMipMaps = false;
  13680. }
  13681. // Upload data if needed. The texture won't be ready until then.
  13682. if (data) {
  13683. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13684. }
  13685. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13686. // Filters
  13687. if (data && generateMipMaps) {
  13688. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13689. }
  13690. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13693. }
  13694. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13695. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13696. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13697. }
  13698. else {
  13699. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13700. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13702. }
  13703. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13704. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13705. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13706. return texture;
  13707. };
  13708. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13709. var _this = this;
  13710. if (onLoad === void 0) { onLoad = null; }
  13711. if (onError === void 0) { onError = null; }
  13712. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13713. if (invertY === void 0) { invertY = false; }
  13714. var gl = this._gl;
  13715. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13716. scene._addPendingData(texture);
  13717. texture.url = url;
  13718. this._internalTexturesCache.push(texture);
  13719. var onerror = function (request, exception) {
  13720. scene._removePendingData(texture);
  13721. if (onError && request) {
  13722. onError(request.status + " " + request.statusText, exception);
  13723. }
  13724. };
  13725. var internalCallback = function (data) {
  13726. var width = texture.width;
  13727. var faceDataArrays = callback(data);
  13728. if (!faceDataArrays) {
  13729. return;
  13730. }
  13731. if (mipmmapGenerator) {
  13732. var textureType = _this._getWebGLTextureType(type);
  13733. var internalFormat = _this._getInternalFormat(format);
  13734. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13735. var needConversion = false;
  13736. if (internalFormat === gl.RGB) {
  13737. internalFormat = gl.RGBA;
  13738. needConversion = true;
  13739. }
  13740. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13741. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13742. var mipData = mipmmapGenerator(faceDataArrays);
  13743. for (var level = 0; level < mipData.length; level++) {
  13744. var mipSize = width >> level;
  13745. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13746. var mipFaceData = mipData[level][faceIndex];
  13747. if (needConversion) {
  13748. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13749. }
  13750. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13751. }
  13752. }
  13753. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13754. }
  13755. else {
  13756. texture.generateMipMaps = !noMipmap;
  13757. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13758. }
  13759. texture.isReady = true;
  13760. // this.resetTextureCache();
  13761. scene._removePendingData(texture);
  13762. if (onLoad) {
  13763. onLoad();
  13764. }
  13765. };
  13766. this._loadFile(url, function (data) {
  13767. internalCallback(data);
  13768. }, undefined, scene.database, true, onerror);
  13769. return texture;
  13770. };
  13771. ;
  13772. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13773. if (compression === void 0) { compression = null; }
  13774. var internalFormat = this._getInternalFormat(format);
  13775. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13776. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13777. if (!this._doNotHandleContextLost) {
  13778. texture._bufferView = data;
  13779. texture.format = format;
  13780. texture.invertY = invertY;
  13781. texture._compression = compression;
  13782. }
  13783. if (texture.width % 4 !== 0) {
  13784. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13785. }
  13786. if (compression && data) {
  13787. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13788. }
  13789. else {
  13790. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13791. }
  13792. if (texture.generateMipMaps) {
  13793. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13794. }
  13795. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13796. // this.resetTextureCache();
  13797. texture.isReady = true;
  13798. };
  13799. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13800. if (compression === void 0) { compression = null; }
  13801. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13802. texture.baseWidth = width;
  13803. texture.baseHeight = height;
  13804. texture.baseDepth = depth;
  13805. texture.width = width;
  13806. texture.height = height;
  13807. texture.depth = depth;
  13808. texture.format = format;
  13809. texture.generateMipMaps = generateMipMaps;
  13810. texture.samplingMode = samplingMode;
  13811. texture.is3D = true;
  13812. if (!this._doNotHandleContextLost) {
  13813. texture._bufferView = data;
  13814. }
  13815. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13816. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13817. // Filters
  13818. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13819. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13820. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13821. if (generateMipMaps) {
  13822. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13823. }
  13824. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13825. this._internalTexturesCache.push(texture);
  13826. return texture;
  13827. };
  13828. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13829. var gl = this._gl;
  13830. if (!gl) {
  13831. return;
  13832. }
  13833. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13834. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13835. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13836. if (!noMipmap && !isCompressed) {
  13837. gl.generateMipmap(gl.TEXTURE_2D);
  13838. }
  13839. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13840. // this.resetTextureCache();
  13841. if (scene) {
  13842. scene._removePendingData(texture);
  13843. }
  13844. texture.onLoadedObservable.notifyObservers(texture);
  13845. texture.onLoadedObservable.clear();
  13846. };
  13847. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13848. var _this = this;
  13849. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13850. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13851. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13852. var gl = this._gl;
  13853. if (!gl) {
  13854. return;
  13855. }
  13856. if (!texture._webGLTexture) {
  13857. // this.resetTextureCache();
  13858. if (scene) {
  13859. scene._removePendingData(texture);
  13860. }
  13861. return;
  13862. }
  13863. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13864. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13865. texture.baseWidth = width;
  13866. texture.baseHeight = height;
  13867. texture.width = potWidth;
  13868. texture.height = potHeight;
  13869. texture.isReady = true;
  13870. if (processFunction(potWidth, potHeight, function () {
  13871. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13872. })) {
  13873. // Returning as texture needs extra async steps
  13874. return;
  13875. }
  13876. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13877. };
  13878. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13879. // Create new RGBA data container.
  13880. var rgbaData;
  13881. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13882. rgbaData = new Float32Array(width * height * 4);
  13883. }
  13884. else {
  13885. rgbaData = new Uint32Array(width * height * 4);
  13886. }
  13887. // Convert each pixel.
  13888. for (var x = 0; x < width; x++) {
  13889. for (var y = 0; y < height; y++) {
  13890. var index = (y * width + x) * 3;
  13891. var newIndex = (y * width + x) * 4;
  13892. // Map Old Value to new value.
  13893. rgbaData[newIndex + 0] = rgbData[index + 0];
  13894. rgbaData[newIndex + 1] = rgbData[index + 1];
  13895. rgbaData[newIndex + 2] = rgbData[index + 2];
  13896. // Add fully opaque alpha channel.
  13897. rgbaData[newIndex + 3] = 1;
  13898. }
  13899. }
  13900. return rgbaData;
  13901. };
  13902. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13903. var gl = this._gl;
  13904. if (texture._framebuffer) {
  13905. gl.deleteFramebuffer(texture._framebuffer);
  13906. texture._framebuffer = null;
  13907. }
  13908. if (texture._depthStencilBuffer) {
  13909. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13910. texture._depthStencilBuffer = null;
  13911. }
  13912. if (texture._MSAAFramebuffer) {
  13913. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13914. texture._MSAAFramebuffer = null;
  13915. }
  13916. if (texture._MSAARenderBuffer) {
  13917. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13918. texture._MSAARenderBuffer = null;
  13919. }
  13920. };
  13921. Engine.prototype._releaseTexture = function (texture) {
  13922. var gl = this._gl;
  13923. this._releaseFramebufferObjects(texture);
  13924. gl.deleteTexture(texture._webGLTexture);
  13925. // Unbind channels
  13926. this.unbindAllTextures();
  13927. var index = this._internalTexturesCache.indexOf(texture);
  13928. if (index !== -1) {
  13929. this._internalTexturesCache.splice(index, 1);
  13930. }
  13931. // Integrated fixed lod samplers.
  13932. if (texture._lodTextureHigh) {
  13933. texture._lodTextureHigh.dispose();
  13934. }
  13935. if (texture._lodTextureMid) {
  13936. texture._lodTextureMid.dispose();
  13937. }
  13938. if (texture._lodTextureLow) {
  13939. texture._lodTextureLow.dispose();
  13940. }
  13941. };
  13942. Engine.prototype.setProgram = function (program) {
  13943. if (this._currentProgram !== program) {
  13944. this._gl.useProgram(program);
  13945. this._currentProgram = program;
  13946. }
  13947. };
  13948. Engine.prototype.bindSamplers = function (effect) {
  13949. this.setProgram(effect.getProgram());
  13950. var samplers = effect.getSamplers();
  13951. for (var index = 0; index < samplers.length; index++) {
  13952. var uniform = effect.getUniform(samplers[index]);
  13953. if (uniform) {
  13954. this._boundUniforms[index] = uniform;
  13955. }
  13956. }
  13957. this._currentEffect = null;
  13958. };
  13959. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13960. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13961. return;
  13962. }
  13963. // Remove
  13964. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13965. // Bind last to it
  13966. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13967. // Bind to dummy
  13968. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13969. };
  13970. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13971. if (!internalTexture) {
  13972. return -1;
  13973. }
  13974. internalTexture._initialSlot = channel;
  13975. if (this.disableTextureBindingOptimization) {
  13976. if (channel !== internalTexture._designatedSlot) {
  13977. this._textureCollisions.addCount(1, false);
  13978. }
  13979. }
  13980. else {
  13981. if (channel !== internalTexture._designatedSlot) {
  13982. if (internalTexture._designatedSlot > -1) {
  13983. return internalTexture._designatedSlot;
  13984. }
  13985. else {
  13986. // No slot for this texture, let's pick a new one (if we find a free slot)
  13987. if (this._nextFreeTextureSlots.length) {
  13988. return this._nextFreeTextureSlots[0];
  13989. }
  13990. // We need to recycle the oldest bound texture, sorry.
  13991. this._textureCollisions.addCount(1, false);
  13992. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13993. }
  13994. }
  13995. }
  13996. return channel;
  13997. };
  13998. Engine.prototype._linkTrackers = function (previous, next) {
  13999. previous.next = next;
  14000. next.previous = previous;
  14001. };
  14002. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14003. var currentSlot = internalTexture._designatedSlot;
  14004. if (currentSlot === -1) {
  14005. return -1;
  14006. }
  14007. internalTexture._designatedSlot = -1;
  14008. if (this.disableTextureBindingOptimization) {
  14009. return -1;
  14010. }
  14011. // Remove from bound list
  14012. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14013. // Free the slot
  14014. this._boundTexturesCache[currentSlot] = null;
  14015. this._nextFreeTextureSlots.push(currentSlot);
  14016. return currentSlot;
  14017. };
  14018. Engine.prototype._activateCurrentTexture = function () {
  14019. if (this._currentTextureChannel !== this._activeChannel) {
  14020. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14021. this._currentTextureChannel = this._activeChannel;
  14022. }
  14023. };
  14024. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14025. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14026. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14027. this._activeChannel = texture._designatedSlot;
  14028. }
  14029. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14030. var isTextureForRendering = texture && texture._initialSlot > -1;
  14031. if (currentTextureBound !== texture) {
  14032. if (currentTextureBound) {
  14033. this._removeDesignatedSlot(currentTextureBound);
  14034. }
  14035. this._activateCurrentTexture();
  14036. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14037. this._boundTexturesCache[this._activeChannel] = texture;
  14038. if (texture) {
  14039. if (!this.disableTextureBindingOptimization) {
  14040. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14041. if (slotIndex > -1) {
  14042. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14043. }
  14044. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14045. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14046. }
  14047. texture._designatedSlot = this._activeChannel;
  14048. }
  14049. }
  14050. else if (forTextureDataUpdate) {
  14051. this._activateCurrentTexture();
  14052. }
  14053. if (isTextureForRendering && !forTextureDataUpdate) {
  14054. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14055. }
  14056. };
  14057. Engine.prototype._bindTexture = function (channel, texture) {
  14058. if (channel < 0) {
  14059. return;
  14060. }
  14061. if (texture) {
  14062. channel = this._getCorrectTextureChannel(channel, texture);
  14063. }
  14064. this._activeChannel = channel;
  14065. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14066. };
  14067. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14068. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14069. };
  14070. Engine.prototype.unbindAllTextures = function () {
  14071. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14072. this._activeChannel = channel;
  14073. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14074. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14075. if (this.webGLVersion > 1) {
  14076. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14077. }
  14078. }
  14079. };
  14080. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14081. if (channel < 0) {
  14082. return;
  14083. }
  14084. if (uniform) {
  14085. this._boundUniforms[channel] = uniform;
  14086. }
  14087. this._setTexture(channel, texture);
  14088. };
  14089. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14090. var uniform = this._boundUniforms[sourceSlot];
  14091. if (uniform._currentState === destination) {
  14092. return;
  14093. }
  14094. this._gl.uniform1i(uniform, destination);
  14095. uniform._currentState = destination;
  14096. };
  14097. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14098. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14099. // Not ready?
  14100. if (!texture) {
  14101. if (this._boundTexturesCache[channel] != null) {
  14102. this._activeChannel = channel;
  14103. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14104. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14105. if (this.webGLVersion > 1) {
  14106. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14107. }
  14108. }
  14109. return false;
  14110. }
  14111. // Video
  14112. if (texture.video) {
  14113. this._activeChannel = channel;
  14114. texture.update();
  14115. }
  14116. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14117. texture.delayLoad();
  14118. return false;
  14119. }
  14120. var internalTexture;
  14121. if (texture.isReady()) {
  14122. internalTexture = texture.getInternalTexture();
  14123. }
  14124. else if (texture.isCube) {
  14125. internalTexture = this.emptyCubeTexture;
  14126. }
  14127. else if (texture.is3D) {
  14128. internalTexture = this.emptyTexture3D;
  14129. }
  14130. else {
  14131. internalTexture = this.emptyTexture;
  14132. }
  14133. if (!isPartOfTextureArray) {
  14134. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14135. }
  14136. if (this._boundTexturesCache[channel] === internalTexture) {
  14137. this._moveBoundTextureOnTop(internalTexture);
  14138. if (!isPartOfTextureArray) {
  14139. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14140. }
  14141. return false;
  14142. }
  14143. this._activeChannel = channel;
  14144. if (internalTexture && internalTexture.is3D) {
  14145. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14146. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14147. internalTexture._cachedWrapU = texture.wrapU;
  14148. switch (texture.wrapU) {
  14149. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14150. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14151. break;
  14152. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14153. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14154. break;
  14155. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14156. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14157. break;
  14158. }
  14159. }
  14160. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14161. internalTexture._cachedWrapV = texture.wrapV;
  14162. switch (texture.wrapV) {
  14163. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14164. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14165. break;
  14166. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14167. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14168. break;
  14169. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14170. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14171. break;
  14172. }
  14173. }
  14174. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14175. internalTexture._cachedWrapR = texture.wrapR;
  14176. switch (texture.wrapR) {
  14177. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14178. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14179. break;
  14180. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14181. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14182. break;
  14183. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14184. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14185. break;
  14186. }
  14187. }
  14188. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14189. }
  14190. else if (internalTexture && internalTexture.isCube) {
  14191. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14192. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14193. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14194. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14195. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14196. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14197. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14198. }
  14199. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14200. }
  14201. else {
  14202. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14203. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14204. internalTexture._cachedWrapU = texture.wrapU;
  14205. switch (texture.wrapU) {
  14206. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14207. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14208. break;
  14209. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14210. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14211. break;
  14212. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14213. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14214. break;
  14215. }
  14216. }
  14217. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14218. internalTexture._cachedWrapV = texture.wrapV;
  14219. switch (texture.wrapV) {
  14220. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14221. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14222. break;
  14223. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14224. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14225. break;
  14226. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14227. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14228. break;
  14229. }
  14230. }
  14231. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14232. }
  14233. return true;
  14234. };
  14235. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14236. if (channel < 0 || !uniform) {
  14237. return;
  14238. }
  14239. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14240. this._textureUnits = new Int32Array(textures.length);
  14241. }
  14242. for (var i = 0; i < textures.length; i++) {
  14243. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14244. }
  14245. this._gl.uniform1iv(uniform, this._textureUnits);
  14246. for (var index = 0; index < textures.length; index++) {
  14247. this._setTexture(this._textureUnits[index], textures[index], true);
  14248. }
  14249. };
  14250. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14251. var internalTexture = texture.getInternalTexture();
  14252. if (!internalTexture) {
  14253. return;
  14254. }
  14255. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14256. var value = texture.anisotropicFilteringLevel;
  14257. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14258. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14259. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14260. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14261. }
  14262. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14263. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14264. internalTexture._cachedAnisotropicFilteringLevel = value;
  14265. }
  14266. };
  14267. Engine.prototype.readPixels = function (x, y, width, height) {
  14268. var data = new Uint8Array(height * width * 4);
  14269. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14270. return data;
  14271. };
  14272. /**
  14273. * Add an externaly attached data from its key.
  14274. * This method call will fail and return false, if such key already exists.
  14275. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14276. * @param key the unique key that identifies the data
  14277. * @param data the data object to associate to the key for this Engine instance
  14278. * @return true if no such key were already present and the data was added successfully, false otherwise
  14279. */
  14280. Engine.prototype.addExternalData = function (key, data) {
  14281. if (!this._externalData) {
  14282. this._externalData = new BABYLON.StringDictionary();
  14283. }
  14284. return this._externalData.add(key, data);
  14285. };
  14286. /**
  14287. * Get an externaly attached data from its key
  14288. * @param key the unique key that identifies the data
  14289. * @return the associated data, if present (can be null), or undefined if not present
  14290. */
  14291. Engine.prototype.getExternalData = function (key) {
  14292. if (!this._externalData) {
  14293. this._externalData = new BABYLON.StringDictionary();
  14294. }
  14295. return this._externalData.get(key);
  14296. };
  14297. /**
  14298. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14299. * @param key the unique key that identifies the data
  14300. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14301. * @return the associated data, can be null if the factory returned null.
  14302. */
  14303. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14304. if (!this._externalData) {
  14305. this._externalData = new BABYLON.StringDictionary();
  14306. }
  14307. return this._externalData.getOrAddWithFactory(key, factory);
  14308. };
  14309. /**
  14310. * Remove an externaly attached data from the Engine instance
  14311. * @param key the unique key that identifies the data
  14312. * @return true if the data was successfully removed, false if it doesn't exist
  14313. */
  14314. Engine.prototype.removeExternalData = function (key) {
  14315. if (!this._externalData) {
  14316. this._externalData = new BABYLON.StringDictionary();
  14317. }
  14318. return this._externalData.remove(key);
  14319. };
  14320. Engine.prototype.unbindAllAttributes = function () {
  14321. if (this._mustWipeVertexAttributes) {
  14322. this._mustWipeVertexAttributes = false;
  14323. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14324. this._gl.disableVertexAttribArray(i);
  14325. this._vertexAttribArraysEnabled[i] = false;
  14326. this._currentBufferPointers[i].active = false;
  14327. }
  14328. return;
  14329. }
  14330. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14331. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14332. continue;
  14333. }
  14334. this._gl.disableVertexAttribArray(i);
  14335. this._vertexAttribArraysEnabled[i] = false;
  14336. this._currentBufferPointers[i].active = false;
  14337. }
  14338. };
  14339. Engine.prototype.releaseEffects = function () {
  14340. for (var name in this._compiledEffects) {
  14341. this._deleteProgram(this._compiledEffects[name]._program);
  14342. }
  14343. this._compiledEffects = {};
  14344. };
  14345. // Dispose
  14346. Engine.prototype.dispose = function () {
  14347. this.hideLoadingUI();
  14348. this.stopRenderLoop();
  14349. // Release postProcesses
  14350. while (this.postProcesses.length) {
  14351. this.postProcesses[0].dispose();
  14352. }
  14353. // Empty texture
  14354. if (this._emptyTexture) {
  14355. this._releaseTexture(this._emptyTexture);
  14356. this._emptyTexture = null;
  14357. }
  14358. if (this._emptyCubeTexture) {
  14359. this._releaseTexture(this._emptyCubeTexture);
  14360. this._emptyCubeTexture = null;
  14361. }
  14362. // Rescale PP
  14363. if (this._rescalePostProcess) {
  14364. this._rescalePostProcess.dispose();
  14365. }
  14366. // Release scenes
  14367. while (this.scenes.length) {
  14368. this.scenes[0].dispose();
  14369. }
  14370. // Release audio engine
  14371. if (Engine.audioEngine) {
  14372. Engine.audioEngine.dispose();
  14373. }
  14374. // Release effects
  14375. this.releaseEffects();
  14376. // Unbind
  14377. this.unbindAllAttributes();
  14378. if (this._dummyFramebuffer) {
  14379. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14380. }
  14381. //WebVR
  14382. this.disableVR();
  14383. // Events
  14384. if (BABYLON.Tools.IsWindowObjectExist()) {
  14385. window.removeEventListener("blur", this._onBlur);
  14386. window.removeEventListener("focus", this._onFocus);
  14387. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14388. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14389. if (this._renderingCanvas) {
  14390. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14391. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14392. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14393. if (!this._doNotHandleContextLost) {
  14394. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14395. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14396. }
  14397. }
  14398. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14399. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14400. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14401. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14402. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14403. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14404. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14405. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14406. if (this._onVrDisplayConnect) {
  14407. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14408. if (this._onVrDisplayDisconnect) {
  14409. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14410. }
  14411. if (this._onVrDisplayPresentChange) {
  14412. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14413. }
  14414. this._onVrDisplayConnect = null;
  14415. this._onVrDisplayDisconnect = null;
  14416. }
  14417. }
  14418. // Remove from Instances
  14419. var index = Engine.Instances.indexOf(this);
  14420. if (index >= 0) {
  14421. Engine.Instances.splice(index, 1);
  14422. }
  14423. this._workingCanvas = null;
  14424. this._workingContext = null;
  14425. this._currentBufferPointers = [];
  14426. this._renderingCanvas = null;
  14427. this._currentProgram = null;
  14428. this.onResizeObservable.clear();
  14429. this.onCanvasBlurObservable.clear();
  14430. this.onCanvasFocusObservable.clear();
  14431. this.onCanvasPointerOutObservable.clear();
  14432. this.onBeginFrameObservable.clear();
  14433. this.onEndFrameObservable.clear();
  14434. BABYLON.Effect.ResetCache();
  14435. // Abort active requests
  14436. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14437. var request = _a[_i];
  14438. request.abort();
  14439. }
  14440. };
  14441. // Loading screen
  14442. Engine.prototype.displayLoadingUI = function () {
  14443. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14444. return;
  14445. }
  14446. var loadingScreen = this.loadingScreen;
  14447. if (loadingScreen) {
  14448. loadingScreen.displayLoadingUI();
  14449. }
  14450. };
  14451. Engine.prototype.hideLoadingUI = function () {
  14452. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14453. return;
  14454. }
  14455. var loadingScreen = this.loadingScreen;
  14456. if (loadingScreen) {
  14457. loadingScreen.hideLoadingUI();
  14458. }
  14459. };
  14460. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14461. get: function () {
  14462. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14463. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14464. return this._loadingScreen;
  14465. },
  14466. set: function (loadingScreen) {
  14467. this._loadingScreen = loadingScreen;
  14468. },
  14469. enumerable: true,
  14470. configurable: true
  14471. });
  14472. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14473. set: function (text) {
  14474. this.loadingScreen.loadingUIText = text;
  14475. },
  14476. enumerable: true,
  14477. configurable: true
  14478. });
  14479. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14480. set: function (color) {
  14481. this.loadingScreen.loadingUIBackgroundColor = color;
  14482. },
  14483. enumerable: true,
  14484. configurable: true
  14485. });
  14486. Engine.prototype.attachContextLostEvent = function (callback) {
  14487. if (this._renderingCanvas) {
  14488. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14489. }
  14490. };
  14491. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14492. if (this._renderingCanvas) {
  14493. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14494. }
  14495. };
  14496. Engine.prototype.getVertexShaderSource = function (program) {
  14497. var shaders = this._gl.getAttachedShaders(program);
  14498. if (!shaders) {
  14499. return null;
  14500. }
  14501. return this._gl.getShaderSource(shaders[0]);
  14502. };
  14503. Engine.prototype.getFragmentShaderSource = function (program) {
  14504. var shaders = this._gl.getAttachedShaders(program);
  14505. if (!shaders) {
  14506. return null;
  14507. }
  14508. return this._gl.getShaderSource(shaders[1]);
  14509. };
  14510. Engine.prototype.getError = function () {
  14511. return this._gl.getError();
  14512. };
  14513. // FPS
  14514. Engine.prototype.getFps = function () {
  14515. return this._fps;
  14516. };
  14517. Engine.prototype.getDeltaTime = function () {
  14518. return this._deltaTime;
  14519. };
  14520. Engine.prototype._measureFps = function () {
  14521. this._performanceMonitor.sampleFrame();
  14522. this._fps = this._performanceMonitor.averageFPS;
  14523. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14524. };
  14525. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14526. if (faceIndex === void 0) { faceIndex = -1; }
  14527. var gl = this._gl;
  14528. if (!this._dummyFramebuffer) {
  14529. var dummy = gl.createFramebuffer();
  14530. if (!dummy) {
  14531. throw new Error("Unable to create dummy framebuffer");
  14532. }
  14533. this._dummyFramebuffer = dummy;
  14534. }
  14535. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14536. if (faceIndex > -1) {
  14537. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14538. }
  14539. else {
  14540. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14541. }
  14542. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14543. var buffer;
  14544. switch (readType) {
  14545. case gl.UNSIGNED_BYTE:
  14546. buffer = new Uint8Array(4 * width * height);
  14547. readType = gl.UNSIGNED_BYTE;
  14548. break;
  14549. default:
  14550. buffer = new Float32Array(4 * width * height);
  14551. readType = gl.FLOAT;
  14552. break;
  14553. }
  14554. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14555. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14556. return buffer;
  14557. };
  14558. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14559. if (this._webGLVersion > 1) {
  14560. return this._caps.colorBufferFloat;
  14561. }
  14562. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14563. };
  14564. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14565. if (this._webGLVersion > 1) {
  14566. return this._caps.colorBufferFloat;
  14567. }
  14568. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14569. };
  14570. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14571. Engine.prototype._canRenderToFramebuffer = function (type) {
  14572. var gl = this._gl;
  14573. //clear existing errors
  14574. while (gl.getError() !== gl.NO_ERROR) { }
  14575. var successful = true;
  14576. var texture = gl.createTexture();
  14577. gl.bindTexture(gl.TEXTURE_2D, texture);
  14578. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14579. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14580. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14581. var fb = gl.createFramebuffer();
  14582. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14583. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14584. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14585. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14586. successful = successful && (gl.getError() === gl.NO_ERROR);
  14587. //try render by clearing frame buffer's color buffer
  14588. if (successful) {
  14589. gl.clear(gl.COLOR_BUFFER_BIT);
  14590. successful = successful && (gl.getError() === gl.NO_ERROR);
  14591. }
  14592. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14593. if (successful) {
  14594. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14595. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14596. var readFormat = gl.RGBA;
  14597. var readType = gl.UNSIGNED_BYTE;
  14598. var buffer = new Uint8Array(4);
  14599. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14600. successful = successful && (gl.getError() === gl.NO_ERROR);
  14601. }
  14602. //clean up
  14603. gl.deleteTexture(texture);
  14604. gl.deleteFramebuffer(fb);
  14605. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14606. //clear accumulated errors
  14607. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14608. return successful;
  14609. };
  14610. Engine.prototype._getWebGLTextureType = function (type) {
  14611. if (type === Engine.TEXTURETYPE_FLOAT) {
  14612. return this._gl.FLOAT;
  14613. }
  14614. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14615. // Add Half Float Constant.
  14616. return this._gl.HALF_FLOAT_OES;
  14617. }
  14618. return this._gl.UNSIGNED_BYTE;
  14619. };
  14620. ;
  14621. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  14622. if (this._webGLVersion === 1) {
  14623. return this._gl.RGBA;
  14624. }
  14625. if (type === Engine.TEXTURETYPE_FLOAT) {
  14626. return this._gl.RGBA32F;
  14627. }
  14628. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14629. return this._gl.RGBA16F;
  14630. }
  14631. return this._gl.RGBA;
  14632. };
  14633. ;
  14634. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14635. if (type === Engine.TEXTURETYPE_FLOAT) {
  14636. return this._gl.RGBA32F;
  14637. }
  14638. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14639. return this._gl.RGBA16F;
  14640. }
  14641. return this._gl.RGBA8;
  14642. };
  14643. ;
  14644. Engine.prototype.createQuery = function () {
  14645. return this._gl.createQuery();
  14646. };
  14647. Engine.prototype.deleteQuery = function (query) {
  14648. this._gl.deleteQuery(query);
  14649. return this;
  14650. };
  14651. Engine.prototype.isQueryResultAvailable = function (query) {
  14652. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14653. };
  14654. Engine.prototype.getQueryResult = function (query) {
  14655. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14656. };
  14657. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14658. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14659. this._gl.beginQuery(glAlgorithm, query);
  14660. return this;
  14661. };
  14662. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14663. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14664. this._gl.endQuery(glAlgorithm);
  14665. return this;
  14666. };
  14667. /* Time queries */
  14668. Engine.prototype._createTimeQuery = function () {
  14669. var timerQuery = this._caps.timerQuery;
  14670. if (timerQuery.createQueryEXT) {
  14671. return timerQuery.createQueryEXT();
  14672. }
  14673. return this.createQuery();
  14674. };
  14675. Engine.prototype._deleteTimeQuery = function (query) {
  14676. var timerQuery = this._caps.timerQuery;
  14677. if (timerQuery.deleteQueryEXT) {
  14678. timerQuery.deleteQueryEXT(query);
  14679. return;
  14680. }
  14681. this.deleteQuery(query);
  14682. };
  14683. Engine.prototype._getTimeQueryResult = function (query) {
  14684. var timerQuery = this._caps.timerQuery;
  14685. if (timerQuery.getQueryObjectEXT) {
  14686. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14687. }
  14688. return this.getQueryResult(query);
  14689. };
  14690. Engine.prototype._getTimeQueryAvailability = function (query) {
  14691. var timerQuery = this._caps.timerQuery;
  14692. if (timerQuery.getQueryObjectEXT) {
  14693. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14694. }
  14695. return this.isQueryResultAvailable(query);
  14696. };
  14697. Engine.prototype.startTimeQuery = function () {
  14698. var timerQuery = this._caps.timerQuery;
  14699. if (!timerQuery) {
  14700. return null;
  14701. }
  14702. var token = new BABYLON._TimeToken();
  14703. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14704. if (this._caps.canUseTimestampForTimerQuery) {
  14705. token._startTimeQuery = this._createTimeQuery();
  14706. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14707. }
  14708. else {
  14709. if (this._currentNonTimestampToken) {
  14710. return this._currentNonTimestampToken;
  14711. }
  14712. token._timeElapsedQuery = this._createTimeQuery();
  14713. if (timerQuery.beginQueryEXT) {
  14714. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14715. }
  14716. else {
  14717. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14718. }
  14719. this._currentNonTimestampToken = token;
  14720. }
  14721. return token;
  14722. };
  14723. Engine.prototype.endTimeQuery = function (token) {
  14724. var timerQuery = this._caps.timerQuery;
  14725. if (!timerQuery || !token) {
  14726. return -1;
  14727. }
  14728. if (this._caps.canUseTimestampForTimerQuery) {
  14729. if (!token._startTimeQuery) {
  14730. return -1;
  14731. }
  14732. if (!token._endTimeQuery) {
  14733. token._endTimeQuery = this._createTimeQuery();
  14734. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14735. }
  14736. }
  14737. else if (!token._timeElapsedQueryEnded) {
  14738. if (!token._timeElapsedQuery) {
  14739. return -1;
  14740. }
  14741. if (timerQuery.endQueryEXT) {
  14742. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14743. }
  14744. else {
  14745. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14746. }
  14747. token._timeElapsedQueryEnded = true;
  14748. }
  14749. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14750. var available = false;
  14751. if (token._endTimeQuery) {
  14752. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14753. }
  14754. else if (token._timeElapsedQuery) {
  14755. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14756. }
  14757. if (available && !disjoint) {
  14758. var result = 0;
  14759. if (this._caps.canUseTimestampForTimerQuery) {
  14760. if (!token._startTimeQuery || !token._endTimeQuery) {
  14761. return -1;
  14762. }
  14763. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14764. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14765. result = timeEnd - timeStart;
  14766. this._deleteTimeQuery(token._startTimeQuery);
  14767. this._deleteTimeQuery(token._endTimeQuery);
  14768. token._startTimeQuery = null;
  14769. token._endTimeQuery = null;
  14770. }
  14771. else {
  14772. if (!token._timeElapsedQuery) {
  14773. return -1;
  14774. }
  14775. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14776. this._deleteTimeQuery(token._timeElapsedQuery);
  14777. token._timeElapsedQuery = null;
  14778. token._timeElapsedQueryEnded = false;
  14779. this._currentNonTimestampToken = null;
  14780. }
  14781. return result;
  14782. }
  14783. return -1;
  14784. };
  14785. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14786. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14787. };
  14788. // Transform feedback
  14789. Engine.prototype.createTransformFeedback = function () {
  14790. return this._gl.createTransformFeedback();
  14791. };
  14792. Engine.prototype.deleteTransformFeedback = function (value) {
  14793. this._gl.deleteTransformFeedback(value);
  14794. };
  14795. Engine.prototype.bindTransformFeedback = function (value) {
  14796. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14797. };
  14798. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14799. if (usePoints === void 0) { usePoints = true; }
  14800. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14801. };
  14802. Engine.prototype.endTransformFeedback = function () {
  14803. this._gl.endTransformFeedback();
  14804. };
  14805. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14806. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14807. };
  14808. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14809. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14810. };
  14811. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14812. var _this = this;
  14813. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14814. this._activeRequests.push(request);
  14815. request.onCompleteObservable.add(function (request) {
  14816. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14817. });
  14818. return request;
  14819. };
  14820. /** @ignore */
  14821. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14822. var _this = this;
  14823. return new Promise(function (resolve, reject) {
  14824. _this._loadFile(url, function (data) {
  14825. resolve(data);
  14826. }, undefined, database, useArrayBuffer, function (request, exception) {
  14827. reject(exception);
  14828. });
  14829. });
  14830. };
  14831. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14832. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14833. var onload = function (data) {
  14834. loadedFiles[index] = data;
  14835. loadedFiles._internalCount++;
  14836. if (loadedFiles._internalCount === 6) {
  14837. onfinish(loadedFiles);
  14838. }
  14839. };
  14840. var onerror = function (request, exception) {
  14841. if (onErrorCallBack && request) {
  14842. onErrorCallBack(request.status + " " + request.statusText, exception);
  14843. }
  14844. };
  14845. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14846. };
  14847. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14848. if (onError === void 0) { onError = null; }
  14849. var loadedFiles = [];
  14850. loadedFiles._internalCount = 0;
  14851. for (var index = 0; index < 6; index++) {
  14852. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14853. }
  14854. };
  14855. // Statics
  14856. Engine.isSupported = function () {
  14857. try {
  14858. var tempcanvas = document.createElement("canvas");
  14859. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14860. return gl != null && !!window.WebGLRenderingContext;
  14861. }
  14862. catch (e) {
  14863. return false;
  14864. }
  14865. };
  14866. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14867. Engine.ExceptionList = [
  14868. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14869. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14870. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14871. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14872. ];
  14873. Engine.Instances = new Array();
  14874. // Const statics
  14875. Engine._ALPHA_DISABLE = 0;
  14876. Engine._ALPHA_ADD = 1;
  14877. Engine._ALPHA_COMBINE = 2;
  14878. Engine._ALPHA_SUBTRACT = 3;
  14879. Engine._ALPHA_MULTIPLY = 4;
  14880. Engine._ALPHA_MAXIMIZED = 5;
  14881. Engine._ALPHA_ONEONE = 6;
  14882. Engine._ALPHA_PREMULTIPLIED = 7;
  14883. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14884. Engine._ALPHA_INTERPOLATE = 9;
  14885. Engine._ALPHA_SCREENMODE = 10;
  14886. Engine._DELAYLOADSTATE_NONE = 0;
  14887. Engine._DELAYLOADSTATE_LOADED = 1;
  14888. Engine._DELAYLOADSTATE_LOADING = 2;
  14889. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14890. Engine._TEXTUREFORMAT_ALPHA = 0;
  14891. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14892. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14893. Engine._TEXTUREFORMAT_RGB = 4;
  14894. Engine._TEXTUREFORMAT_RGBA = 5;
  14895. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14896. Engine._TEXTURETYPE_FLOAT = 1;
  14897. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14898. // Depht or Stencil test Constants.
  14899. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14900. 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.
  14901. 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.
  14902. 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.
  14903. 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.
  14904. 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.
  14905. 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.
  14906. 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.
  14907. // Stencil Actions Constants.
  14908. Engine._KEEP = 0x1E00;
  14909. Engine._REPLACE = 0x1E01;
  14910. Engine._INCR = 0x1E02;
  14911. Engine._DECR = 0x1E03;
  14912. Engine._INVERT = 0x150A;
  14913. Engine._INCR_WRAP = 0x8507;
  14914. Engine._DECR_WRAP = 0x8508;
  14915. // Texture rescaling mode
  14916. Engine._SCALEMODE_FLOOR = 1;
  14917. Engine._SCALEMODE_NEAREST = 2;
  14918. Engine._SCALEMODE_CEILING = 3;
  14919. // Updatable statics so stick with vars here
  14920. Engine.CollisionsEpsilon = 0.001;
  14921. Engine.CodeRepository = "src/";
  14922. Engine.ShadersRepository = "src/Shaders/";
  14923. return Engine;
  14924. }());
  14925. BABYLON.Engine = Engine;
  14926. })(BABYLON || (BABYLON = {}));
  14927. //# sourceMappingURL=babylon.engine.js.map
  14928. var BABYLON;
  14929. (function (BABYLON) {
  14930. /**
  14931. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14932. */
  14933. var Node = /** @class */ (function () {
  14934. /**
  14935. * @constructor
  14936. * @param {string} name - the name and id to be given to this node
  14937. * @param {BABYLON.Scene} the scene this node will be added to
  14938. */
  14939. function Node(name, scene) {
  14940. if (scene === void 0) { scene = null; }
  14941. this.state = "";
  14942. this.metadata = null;
  14943. this.doNotSerialize = false;
  14944. this.animations = new Array();
  14945. this._ranges = {};
  14946. this._isEnabled = true;
  14947. this._isReady = true;
  14948. this._currentRenderId = -1;
  14949. this._parentRenderId = -1;
  14950. /**
  14951. * An event triggered when the mesh is disposed.
  14952. * @type {BABYLON.Observable}
  14953. */
  14954. this.onDisposeObservable = new BABYLON.Observable();
  14955. // Behaviors
  14956. this._behaviors = new Array();
  14957. this.name = name;
  14958. this.id = name;
  14959. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14960. this.uniqueId = this._scene.getUniqueId();
  14961. this._initCache();
  14962. }
  14963. Object.defineProperty(Node.prototype, "parent", {
  14964. get: function () {
  14965. return this._parentNode;
  14966. },
  14967. set: function (parent) {
  14968. if (this._parentNode === parent) {
  14969. return;
  14970. }
  14971. // Remove self from list of children of parent
  14972. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14973. var index = this._parentNode._children.indexOf(this);
  14974. if (index !== -1) {
  14975. this._parentNode._children.splice(index, 1);
  14976. }
  14977. }
  14978. // Store new parent
  14979. this._parentNode = parent;
  14980. // Add as child to new parent
  14981. if (this._parentNode) {
  14982. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  14983. this._parentNode._children = new Array();
  14984. }
  14985. this._parentNode._children.push(this);
  14986. }
  14987. },
  14988. enumerable: true,
  14989. configurable: true
  14990. });
  14991. Node.prototype.getClassName = function () {
  14992. return "Node";
  14993. };
  14994. Object.defineProperty(Node.prototype, "onDispose", {
  14995. set: function (callback) {
  14996. if (this._onDisposeObserver) {
  14997. this.onDisposeObservable.remove(this._onDisposeObserver);
  14998. }
  14999. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15000. },
  15001. enumerable: true,
  15002. configurable: true
  15003. });
  15004. Node.prototype.getScene = function () {
  15005. return this._scene;
  15006. };
  15007. Node.prototype.getEngine = function () {
  15008. return this._scene.getEngine();
  15009. };
  15010. Node.prototype.addBehavior = function (behavior) {
  15011. var _this = this;
  15012. var index = this._behaviors.indexOf(behavior);
  15013. if (index !== -1) {
  15014. return this;
  15015. }
  15016. behavior.init();
  15017. if (this._scene.isLoading) {
  15018. // We defer the attach when the scene will be loaded
  15019. var observer = this._scene.onDataLoadedObservable.add(function () {
  15020. behavior.attach(_this);
  15021. setTimeout(function () {
  15022. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15023. _this._scene.onDataLoadedObservable.remove(observer);
  15024. }, 0);
  15025. });
  15026. }
  15027. else {
  15028. behavior.attach(this);
  15029. }
  15030. this._behaviors.push(behavior);
  15031. return this;
  15032. };
  15033. Node.prototype.removeBehavior = function (behavior) {
  15034. var index = this._behaviors.indexOf(behavior);
  15035. if (index === -1) {
  15036. return this;
  15037. }
  15038. this._behaviors[index].detach();
  15039. this._behaviors.splice(index, 1);
  15040. return this;
  15041. };
  15042. Object.defineProperty(Node.prototype, "behaviors", {
  15043. get: function () {
  15044. return this._behaviors;
  15045. },
  15046. enumerable: true,
  15047. configurable: true
  15048. });
  15049. Node.prototype.getBehaviorByName = function (name) {
  15050. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15051. var behavior = _a[_i];
  15052. if (behavior.name === name) {
  15053. return behavior;
  15054. }
  15055. }
  15056. return null;
  15057. };
  15058. // override it in derived class
  15059. Node.prototype.getWorldMatrix = function () {
  15060. return BABYLON.Matrix.Identity();
  15061. };
  15062. // override it in derived class if you add new variables to the cache
  15063. // and call the parent class method
  15064. Node.prototype._initCache = function () {
  15065. this._cache = {};
  15066. this._cache.parent = undefined;
  15067. };
  15068. Node.prototype.updateCache = function (force) {
  15069. if (!force && this.isSynchronized())
  15070. return;
  15071. this._cache.parent = this.parent;
  15072. this._updateCache();
  15073. };
  15074. // override it in derived class if you add new variables to the cache
  15075. // and call the parent class method if !ignoreParentClass
  15076. Node.prototype._updateCache = function (ignoreParentClass) {
  15077. };
  15078. // override it in derived class if you add new variables to the cache
  15079. Node.prototype._isSynchronized = function () {
  15080. return true;
  15081. };
  15082. Node.prototype._markSyncedWithParent = function () {
  15083. if (this.parent) {
  15084. this._parentRenderId = this.parent._currentRenderId;
  15085. }
  15086. };
  15087. Node.prototype.isSynchronizedWithParent = function () {
  15088. if (!this.parent) {
  15089. return true;
  15090. }
  15091. if (this._parentRenderId !== this.parent._currentRenderId) {
  15092. return false;
  15093. }
  15094. return this.parent.isSynchronized();
  15095. };
  15096. Node.prototype.isSynchronized = function (updateCache) {
  15097. var check = this.hasNewParent();
  15098. check = check || !this.isSynchronizedWithParent();
  15099. check = check || !this._isSynchronized();
  15100. if (updateCache)
  15101. this.updateCache(true);
  15102. return !check;
  15103. };
  15104. Node.prototype.hasNewParent = function (update) {
  15105. if (this._cache.parent === this.parent)
  15106. return false;
  15107. if (update)
  15108. this._cache.parent = this.parent;
  15109. return true;
  15110. };
  15111. /**
  15112. * Is this node ready to be used/rendered
  15113. * @return {boolean} is it ready
  15114. */
  15115. Node.prototype.isReady = function () {
  15116. return this._isReady;
  15117. };
  15118. /**
  15119. * Is this node enabled.
  15120. * 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.
  15121. * @param {boolean} [checkAncestors=true] - 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.
  15122. * @return {boolean} whether this node (and its parent) is enabled.
  15123. * @see setEnabled
  15124. */
  15125. Node.prototype.isEnabled = function (checkAncestors) {
  15126. if (checkAncestors === void 0) { checkAncestors = true; }
  15127. if (checkAncestors === false) {
  15128. return this._isEnabled;
  15129. }
  15130. if (this._isEnabled === false) {
  15131. return false;
  15132. }
  15133. if (this.parent !== undefined && this.parent !== null) {
  15134. return this.parent.isEnabled(checkAncestors);
  15135. }
  15136. return true;
  15137. };
  15138. /**
  15139. * Set the enabled state of this node.
  15140. * @param {boolean} value - the new enabled state
  15141. * @see isEnabled
  15142. */
  15143. Node.prototype.setEnabled = function (value) {
  15144. this._isEnabled = value;
  15145. };
  15146. /**
  15147. * Is this node a descendant of the given node.
  15148. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  15149. * @param {BABYLON.Node} ancestor - The parent node to inspect
  15150. * @see parent
  15151. */
  15152. Node.prototype.isDescendantOf = function (ancestor) {
  15153. if (this.parent) {
  15154. if (this.parent === ancestor) {
  15155. return true;
  15156. }
  15157. return this.parent.isDescendantOf(ancestor);
  15158. }
  15159. return false;
  15160. };
  15161. /**
  15162. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  15163. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  15164. * @param {boolean} directDescendantsOnly 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.
  15165. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  15166. */
  15167. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15168. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15169. if (!this._children) {
  15170. return;
  15171. }
  15172. for (var index = 0; index < this._children.length; index++) {
  15173. var item = this._children[index];
  15174. if (!predicate || predicate(item)) {
  15175. results.push(item);
  15176. }
  15177. if (!directDescendantsOnly) {
  15178. item._getDescendants(results, false, predicate);
  15179. }
  15180. }
  15181. };
  15182. /**
  15183. * Will return all nodes that have this node as ascendant.
  15184. * @param {boolean} directDescendantsOnly 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.
  15185. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  15186. * @return {BABYLON.Node[]} all children nodes of all types.
  15187. */
  15188. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15189. var results = new Array();
  15190. this._getDescendants(results, directDescendantsOnly, predicate);
  15191. return results;
  15192. };
  15193. /**
  15194. * Get all child-meshes of this node.
  15195. */
  15196. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15197. var results = [];
  15198. this._getDescendants(results, directDescendantsOnly, function (node) {
  15199. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15200. });
  15201. return results;
  15202. };
  15203. /**
  15204. * Get all child-transformNodes of this node.
  15205. */
  15206. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15207. var results = [];
  15208. this._getDescendants(results, directDescendantsOnly, function (node) {
  15209. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15210. });
  15211. return results;
  15212. };
  15213. /**
  15214. * Get all direct children of this node.
  15215. */
  15216. Node.prototype.getChildren = function (predicate) {
  15217. return this.getDescendants(true, predicate);
  15218. };
  15219. Node.prototype._setReady = function (state) {
  15220. if (state === this._isReady) {
  15221. return;
  15222. }
  15223. if (!state) {
  15224. this._isReady = false;
  15225. return;
  15226. }
  15227. this._isReady = true;
  15228. if (this.onReady) {
  15229. this.onReady(this);
  15230. }
  15231. };
  15232. Node.prototype.getAnimationByName = function (name) {
  15233. for (var i = 0; i < this.animations.length; i++) {
  15234. var animation = this.animations[i];
  15235. if (animation.name === name) {
  15236. return animation;
  15237. }
  15238. }
  15239. return null;
  15240. };
  15241. Node.prototype.createAnimationRange = function (name, from, to) {
  15242. // check name not already in use
  15243. if (!this._ranges[name]) {
  15244. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15245. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15246. if (this.animations[i]) {
  15247. this.animations[i].createRange(name, from, to);
  15248. }
  15249. }
  15250. }
  15251. };
  15252. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15253. if (deleteFrames === void 0) { deleteFrames = true; }
  15254. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15255. if (this.animations[i]) {
  15256. this.animations[i].deleteRange(name, deleteFrames);
  15257. }
  15258. }
  15259. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15260. };
  15261. Node.prototype.getAnimationRange = function (name) {
  15262. return this._ranges[name];
  15263. };
  15264. /**
  15265. * Will start the animation sequence
  15266. * @param name defines the range frames for animation sequence
  15267. * @param loop defines if the animation should loop (false by default)
  15268. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15269. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15270. * @returns the {BABYLON.Animatable} object created for this animation. If range does not exist, it will return null
  15271. */
  15272. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15273. var range = this.getAnimationRange(name);
  15274. if (!range) {
  15275. return null;
  15276. }
  15277. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15278. };
  15279. Node.prototype.serializeAnimationRanges = function () {
  15280. var serializationRanges = [];
  15281. for (var name in this._ranges) {
  15282. var localRange = this._ranges[name];
  15283. if (!localRange) {
  15284. continue;
  15285. }
  15286. var range = {};
  15287. range.name = name;
  15288. range.from = localRange.from;
  15289. range.to = localRange.to;
  15290. serializationRanges.push(range);
  15291. }
  15292. return serializationRanges;
  15293. };
  15294. // override it in derived class
  15295. Node.prototype.computeWorldMatrix = function (force) {
  15296. return BABYLON.Matrix.Identity();
  15297. };
  15298. Node.prototype.dispose = function () {
  15299. this.parent = null;
  15300. // Callback
  15301. this.onDisposeObservable.notifyObservers(this);
  15302. this.onDisposeObservable.clear();
  15303. // Behaviors
  15304. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15305. var behavior = _a[_i];
  15306. behavior.detach();
  15307. }
  15308. this._behaviors = [];
  15309. };
  15310. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15311. if (parsedNode.ranges) {
  15312. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15313. var data = parsedNode.ranges[index];
  15314. node.createAnimationRange(data.name, data.from, data.to);
  15315. }
  15316. }
  15317. };
  15318. __decorate([
  15319. BABYLON.serialize()
  15320. ], Node.prototype, "name", void 0);
  15321. __decorate([
  15322. BABYLON.serialize()
  15323. ], Node.prototype, "id", void 0);
  15324. __decorate([
  15325. BABYLON.serialize()
  15326. ], Node.prototype, "uniqueId", void 0);
  15327. __decorate([
  15328. BABYLON.serialize()
  15329. ], Node.prototype, "state", void 0);
  15330. __decorate([
  15331. BABYLON.serialize()
  15332. ], Node.prototype, "metadata", void 0);
  15333. return Node;
  15334. }());
  15335. BABYLON.Node = Node;
  15336. })(BABYLON || (BABYLON = {}));
  15337. //# sourceMappingURL=babylon.node.js.map
  15338. var BABYLON;
  15339. (function (BABYLON) {
  15340. var BoundingSphere = /** @class */ (function () {
  15341. function BoundingSphere(minimum, maximum) {
  15342. this.minimum = minimum;
  15343. this.maximum = maximum;
  15344. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15345. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15346. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15347. this.radius = distance * 0.5;
  15348. this.centerWorld = BABYLON.Vector3.Zero();
  15349. this._update(BABYLON.Matrix.Identity());
  15350. }
  15351. // Methods
  15352. BoundingSphere.prototype._update = function (world) {
  15353. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15354. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15355. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15356. };
  15357. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15358. for (var i = 0; i < 6; i++) {
  15359. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15360. return false;
  15361. }
  15362. return true;
  15363. };
  15364. BoundingSphere.prototype.intersectsPoint = function (point) {
  15365. var x = this.centerWorld.x - point.x;
  15366. var y = this.centerWorld.y - point.y;
  15367. var z = this.centerWorld.z - point.z;
  15368. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15369. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15370. return false;
  15371. return true;
  15372. };
  15373. // Statics
  15374. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15375. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15376. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15377. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15378. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15379. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15380. return false;
  15381. return true;
  15382. };
  15383. return BoundingSphere;
  15384. }());
  15385. BABYLON.BoundingSphere = BoundingSphere;
  15386. })(BABYLON || (BABYLON = {}));
  15387. //# sourceMappingURL=babylon.boundingSphere.js.map
  15388. var BABYLON;
  15389. (function (BABYLON) {
  15390. var BoundingBox = /** @class */ (function () {
  15391. function BoundingBox(minimum, maximum) {
  15392. this.minimum = minimum;
  15393. this.maximum = maximum;
  15394. this.vectors = new Array();
  15395. this.vectorsWorld = new Array();
  15396. // Bounding vectors
  15397. this.vectors.push(this.minimum.clone());
  15398. this.vectors.push(this.maximum.clone());
  15399. this.vectors.push(this.minimum.clone());
  15400. this.vectors[2].x = this.maximum.x;
  15401. this.vectors.push(this.minimum.clone());
  15402. this.vectors[3].y = this.maximum.y;
  15403. this.vectors.push(this.minimum.clone());
  15404. this.vectors[4].z = this.maximum.z;
  15405. this.vectors.push(this.maximum.clone());
  15406. this.vectors[5].z = this.minimum.z;
  15407. this.vectors.push(this.maximum.clone());
  15408. this.vectors[6].x = this.minimum.x;
  15409. this.vectors.push(this.maximum.clone());
  15410. this.vectors[7].y = this.minimum.y;
  15411. // OBB
  15412. this.center = this.maximum.add(this.minimum).scale(0.5);
  15413. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15414. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15415. // World
  15416. for (var index = 0; index < this.vectors.length; index++) {
  15417. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15418. }
  15419. this.minimumWorld = BABYLON.Vector3.Zero();
  15420. this.maximumWorld = BABYLON.Vector3.Zero();
  15421. this.centerWorld = BABYLON.Vector3.Zero();
  15422. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15423. this._update(BABYLON.Matrix.Identity());
  15424. }
  15425. // Methods
  15426. BoundingBox.prototype.getWorldMatrix = function () {
  15427. return this._worldMatrix;
  15428. };
  15429. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15430. this._worldMatrix.copyFrom(matrix);
  15431. return this;
  15432. };
  15433. BoundingBox.prototype._update = function (world) {
  15434. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15435. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15436. for (var index = 0; index < this.vectors.length; index++) {
  15437. var v = this.vectorsWorld[index];
  15438. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15439. if (v.x < this.minimumWorld.x)
  15440. this.minimumWorld.x = v.x;
  15441. if (v.y < this.minimumWorld.y)
  15442. this.minimumWorld.y = v.y;
  15443. if (v.z < this.minimumWorld.z)
  15444. this.minimumWorld.z = v.z;
  15445. if (v.x > this.maximumWorld.x)
  15446. this.maximumWorld.x = v.x;
  15447. if (v.y > this.maximumWorld.y)
  15448. this.maximumWorld.y = v.y;
  15449. if (v.z > this.maximumWorld.z)
  15450. this.maximumWorld.z = v.z;
  15451. }
  15452. // Extend
  15453. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15454. this.extendSizeWorld.scaleInPlace(0.5);
  15455. // OBB
  15456. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15457. this.centerWorld.scaleInPlace(0.5);
  15458. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15459. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15460. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15461. this._worldMatrix = world;
  15462. };
  15463. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15464. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15465. };
  15466. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15467. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15468. };
  15469. BoundingBox.prototype.intersectsPoint = function (point) {
  15470. var delta = -BABYLON.Epsilon;
  15471. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15472. return false;
  15473. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15474. return false;
  15475. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15476. return false;
  15477. return true;
  15478. };
  15479. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15480. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15481. };
  15482. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15483. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15484. return false;
  15485. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15486. return false;
  15487. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15488. return false;
  15489. return true;
  15490. };
  15491. // Statics
  15492. BoundingBox.Intersects = function (box0, box1) {
  15493. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15494. return false;
  15495. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15496. return false;
  15497. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15498. return false;
  15499. return true;
  15500. };
  15501. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15502. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15503. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15504. return (num <= (sphereRadius * sphereRadius));
  15505. };
  15506. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15507. for (var p = 0; p < 6; p++) {
  15508. for (var i = 0; i < 8; i++) {
  15509. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15510. return false;
  15511. }
  15512. }
  15513. }
  15514. return true;
  15515. };
  15516. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15517. for (var p = 0; p < 6; p++) {
  15518. var inCount = 8;
  15519. for (var i = 0; i < 8; i++) {
  15520. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15521. --inCount;
  15522. }
  15523. else {
  15524. break;
  15525. }
  15526. }
  15527. if (inCount === 0)
  15528. return false;
  15529. }
  15530. return true;
  15531. };
  15532. return BoundingBox;
  15533. }());
  15534. BABYLON.BoundingBox = BoundingBox;
  15535. })(BABYLON || (BABYLON = {}));
  15536. //# sourceMappingURL=babylon.boundingBox.js.map
  15537. var BABYLON;
  15538. (function (BABYLON) {
  15539. var computeBoxExtents = function (axis, box) {
  15540. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15541. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15542. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15543. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15544. var r = r0 + r1 + r2;
  15545. return {
  15546. min: p - r,
  15547. max: p + r
  15548. };
  15549. };
  15550. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15551. var axisOverlap = function (axis, box0, box1) {
  15552. var result0 = computeBoxExtents(axis, box0);
  15553. var result1 = computeBoxExtents(axis, box1);
  15554. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15555. };
  15556. var BoundingInfo = /** @class */ (function () {
  15557. function BoundingInfo(minimum, maximum) {
  15558. this.minimum = minimum;
  15559. this.maximum = maximum;
  15560. this._isLocked = false;
  15561. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15562. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15563. }
  15564. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15565. get: function () {
  15566. return this._isLocked;
  15567. },
  15568. set: function (value) {
  15569. this._isLocked = value;
  15570. },
  15571. enumerable: true,
  15572. configurable: true
  15573. });
  15574. // Methods
  15575. BoundingInfo.prototype.update = function (world) {
  15576. if (this._isLocked) {
  15577. return;
  15578. }
  15579. this.boundingBox._update(world);
  15580. this.boundingSphere._update(world);
  15581. };
  15582. /**
  15583. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15584. * @param center New center of the bounding info
  15585. * @param extend New extend of the bounding info
  15586. */
  15587. BoundingInfo.prototype.centerOn = function (center, extend) {
  15588. this.minimum = center.subtract(extend);
  15589. this.maximum = center.add(extend);
  15590. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15591. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15592. return this;
  15593. };
  15594. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15595. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15596. return false;
  15597. return this.boundingBox.isInFrustum(frustumPlanes);
  15598. };
  15599. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15600. /**
  15601. * Gets the world distance between the min and max points of the bounding box
  15602. */
  15603. get: function () {
  15604. var boundingBox = this.boundingBox;
  15605. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15606. return size.length();
  15607. },
  15608. enumerable: true,
  15609. configurable: true
  15610. });
  15611. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15612. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15613. };
  15614. BoundingInfo.prototype._checkCollision = function (collider) {
  15615. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15616. };
  15617. BoundingInfo.prototype.intersectsPoint = function (point) {
  15618. if (!this.boundingSphere.centerWorld) {
  15619. return false;
  15620. }
  15621. if (!this.boundingSphere.intersectsPoint(point)) {
  15622. return false;
  15623. }
  15624. if (!this.boundingBox.intersectsPoint(point)) {
  15625. return false;
  15626. }
  15627. return true;
  15628. };
  15629. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15630. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15631. return false;
  15632. }
  15633. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15634. return false;
  15635. }
  15636. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15637. return false;
  15638. }
  15639. if (!precise) {
  15640. return true;
  15641. }
  15642. var box0 = this.boundingBox;
  15643. var box1 = boundingInfo.boundingBox;
  15644. if (!axisOverlap(box0.directions[0], box0, box1))
  15645. return false;
  15646. if (!axisOverlap(box0.directions[1], box0, box1))
  15647. return false;
  15648. if (!axisOverlap(box0.directions[2], box0, box1))
  15649. return false;
  15650. if (!axisOverlap(box1.directions[0], box0, box1))
  15651. return false;
  15652. if (!axisOverlap(box1.directions[1], box0, box1))
  15653. return false;
  15654. if (!axisOverlap(box1.directions[2], box0, box1))
  15655. return false;
  15656. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15657. return false;
  15658. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15659. return false;
  15660. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15661. return false;
  15662. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15663. return false;
  15664. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15665. return false;
  15666. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15667. return false;
  15668. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15669. return false;
  15670. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15671. return false;
  15672. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15673. return false;
  15674. return true;
  15675. };
  15676. return BoundingInfo;
  15677. }());
  15678. BABYLON.BoundingInfo = BoundingInfo;
  15679. })(BABYLON || (BABYLON = {}));
  15680. //# sourceMappingURL=babylon.boundingInfo.js.map
  15681. var BABYLON;
  15682. (function (BABYLON) {
  15683. var TransformNode = /** @class */ (function (_super) {
  15684. __extends(TransformNode, _super);
  15685. function TransformNode(name, scene, isPure) {
  15686. if (scene === void 0) { scene = null; }
  15687. if (isPure === void 0) { isPure = true; }
  15688. var _this = _super.call(this, name, scene) || this;
  15689. // Properties
  15690. _this._rotation = BABYLON.Vector3.Zero();
  15691. _this._scaling = BABYLON.Vector3.One();
  15692. _this._isDirty = false;
  15693. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15694. _this.scalingDeterminant = 1;
  15695. _this.infiniteDistance = false;
  15696. _this.position = BABYLON.Vector3.Zero();
  15697. _this._localWorld = BABYLON.Matrix.Zero();
  15698. _this._worldMatrix = BABYLON.Matrix.Zero();
  15699. _this._worldMatrixDeterminant = 0;
  15700. _this._absolutePosition = BABYLON.Vector3.Zero();
  15701. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15702. _this._postMultiplyPivotMatrix = false;
  15703. _this._isWorldMatrixFrozen = false;
  15704. /**
  15705. * An event triggered after the world matrix is updated
  15706. * @type {BABYLON.Observable}
  15707. */
  15708. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15709. _this._nonUniformScaling = false;
  15710. if (isPure) {
  15711. _this.getScene().addTransformNode(_this);
  15712. }
  15713. return _this;
  15714. }
  15715. Object.defineProperty(TransformNode.prototype, "rotation", {
  15716. /**
  15717. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15718. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15719. * Default : (0.0, 0.0, 0.0)
  15720. */
  15721. get: function () {
  15722. return this._rotation;
  15723. },
  15724. set: function (newRotation) {
  15725. this._rotation = newRotation;
  15726. },
  15727. enumerable: true,
  15728. configurable: true
  15729. });
  15730. Object.defineProperty(TransformNode.prototype, "scaling", {
  15731. /**
  15732. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15733. * Default : (1.0, 1.0, 1.0)
  15734. */
  15735. get: function () {
  15736. return this._scaling;
  15737. },
  15738. /**
  15739. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15740. * Default : (1.0, 1.0, 1.0)
  15741. */
  15742. set: function (newScaling) {
  15743. this._scaling = newScaling;
  15744. },
  15745. enumerable: true,
  15746. configurable: true
  15747. });
  15748. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15749. /**
  15750. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15751. * It's null by default.
  15752. * 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)
  15753. */
  15754. get: function () {
  15755. return this._rotationQuaternion;
  15756. },
  15757. set: function (quaternion) {
  15758. this._rotationQuaternion = quaternion;
  15759. //reset the rotation vector.
  15760. if (quaternion && this.rotation.length()) {
  15761. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15762. }
  15763. },
  15764. enumerable: true,
  15765. configurable: true
  15766. });
  15767. /**
  15768. * Returns the latest update of the World matrix
  15769. * Returns a Matrix.
  15770. */
  15771. TransformNode.prototype.getWorldMatrix = function () {
  15772. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15773. this.computeWorldMatrix();
  15774. }
  15775. return this._worldMatrix;
  15776. };
  15777. /**
  15778. * Returns the latest update of the World matrix determinant.
  15779. */
  15780. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15781. return this._worldMatrixDeterminant;
  15782. };
  15783. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15784. /**
  15785. * Returns directly the latest state of the mesh World matrix.
  15786. * A Matrix is returned.
  15787. */
  15788. get: function () {
  15789. return this._worldMatrix;
  15790. },
  15791. enumerable: true,
  15792. configurable: true
  15793. });
  15794. /**
  15795. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15796. * Returns the AbstractMesh.
  15797. */
  15798. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15799. this._poseMatrix.copyFrom(matrix);
  15800. return this;
  15801. };
  15802. /**
  15803. * Returns the mesh Pose matrix.
  15804. * Returned object : Matrix
  15805. */
  15806. TransformNode.prototype.getPoseMatrix = function () {
  15807. return this._poseMatrix;
  15808. };
  15809. TransformNode.prototype._isSynchronized = function () {
  15810. if (this._isDirty) {
  15811. return false;
  15812. }
  15813. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15814. return false;
  15815. if (this._cache.pivotMatrixUpdated) {
  15816. return false;
  15817. }
  15818. if (this.infiniteDistance) {
  15819. return false;
  15820. }
  15821. if (!this._cache.position.equals(this.position))
  15822. return false;
  15823. if (this.rotationQuaternion) {
  15824. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15825. return false;
  15826. }
  15827. if (!this._cache.rotation.equals(this.rotation))
  15828. return false;
  15829. if (!this._cache.scaling.equals(this.scaling))
  15830. return false;
  15831. return true;
  15832. };
  15833. TransformNode.prototype._initCache = function () {
  15834. _super.prototype._initCache.call(this);
  15835. this._cache.localMatrixUpdated = false;
  15836. this._cache.position = BABYLON.Vector3.Zero();
  15837. this._cache.scaling = BABYLON.Vector3.Zero();
  15838. this._cache.rotation = BABYLON.Vector3.Zero();
  15839. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15840. this._cache.billboardMode = -1;
  15841. };
  15842. TransformNode.prototype.markAsDirty = function (property) {
  15843. if (property === "rotation") {
  15844. this.rotationQuaternion = null;
  15845. }
  15846. this._currentRenderId = Number.MAX_VALUE;
  15847. this._isDirty = true;
  15848. return this;
  15849. };
  15850. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15851. /**
  15852. * Returns the current mesh absolute position.
  15853. * Retuns a Vector3.
  15854. */
  15855. get: function () {
  15856. return this._absolutePosition;
  15857. },
  15858. enumerable: true,
  15859. configurable: true
  15860. });
  15861. /**
  15862. * Sets a new matrix to apply before all other transformation
  15863. * @param matrix defines the transform matrix
  15864. * @returns the current TransformNode
  15865. */
  15866. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  15867. return this.setPivotMatrix(matrix, false);
  15868. };
  15869. /**
  15870. * Sets a new pivot matrix to the current node
  15871. * @param matrix defines the new pivot matrix to use
  15872. * @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
  15873. * @returns the current TransformNode
  15874. */
  15875. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15876. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  15877. this._pivotMatrix = matrix.clone();
  15878. this._cache.pivotMatrixUpdated = true;
  15879. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15880. if (this._postMultiplyPivotMatrix) {
  15881. if (!this._pivotMatrixInverse) {
  15882. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  15883. }
  15884. else {
  15885. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  15886. }
  15887. }
  15888. return this;
  15889. };
  15890. /**
  15891. * Returns the mesh pivot matrix.
  15892. * Default : Identity.
  15893. * A Matrix is returned.
  15894. */
  15895. TransformNode.prototype.getPivotMatrix = function () {
  15896. return this._pivotMatrix;
  15897. };
  15898. /**
  15899. * Prevents the World matrix to be computed any longer.
  15900. * Returns the AbstractMesh.
  15901. */
  15902. TransformNode.prototype.freezeWorldMatrix = function () {
  15903. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  15904. this.computeWorldMatrix(true);
  15905. this._isWorldMatrixFrozen = true;
  15906. return this;
  15907. };
  15908. /**
  15909. * Allows back the World matrix computation.
  15910. * Returns the AbstractMesh.
  15911. */
  15912. TransformNode.prototype.unfreezeWorldMatrix = function () {
  15913. this._isWorldMatrixFrozen = false;
  15914. this.computeWorldMatrix(true);
  15915. return this;
  15916. };
  15917. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  15918. /**
  15919. * True if the World matrix has been frozen.
  15920. * Returns a boolean.
  15921. */
  15922. get: function () {
  15923. return this._isWorldMatrixFrozen;
  15924. },
  15925. enumerable: true,
  15926. configurable: true
  15927. });
  15928. /**
  15929. * Retuns the mesh absolute position in the World.
  15930. * Returns a Vector3.
  15931. */
  15932. TransformNode.prototype.getAbsolutePosition = function () {
  15933. this.computeWorldMatrix();
  15934. return this._absolutePosition;
  15935. };
  15936. /**
  15937. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  15938. * Returns the AbstractMesh.
  15939. */
  15940. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  15941. if (!absolutePosition) {
  15942. return this;
  15943. }
  15944. var absolutePositionX;
  15945. var absolutePositionY;
  15946. var absolutePositionZ;
  15947. if (absolutePosition.x === undefined) {
  15948. if (arguments.length < 3) {
  15949. return this;
  15950. }
  15951. absolutePositionX = arguments[0];
  15952. absolutePositionY = arguments[1];
  15953. absolutePositionZ = arguments[2];
  15954. }
  15955. else {
  15956. absolutePositionX = absolutePosition.x;
  15957. absolutePositionY = absolutePosition.y;
  15958. absolutePositionZ = absolutePosition.z;
  15959. }
  15960. if (this.parent) {
  15961. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15962. invertParentWorldMatrix.invert();
  15963. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  15964. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  15965. }
  15966. else {
  15967. this.position.x = absolutePositionX;
  15968. this.position.y = absolutePositionY;
  15969. this.position.z = absolutePositionZ;
  15970. }
  15971. return this;
  15972. };
  15973. /**
  15974. * Sets the mesh position in its local space.
  15975. * Returns the AbstractMesh.
  15976. */
  15977. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  15978. this.computeWorldMatrix();
  15979. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  15980. return this;
  15981. };
  15982. /**
  15983. * Returns the mesh position in the local space from the current World matrix values.
  15984. * Returns a new Vector3.
  15985. */
  15986. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  15987. this.computeWorldMatrix();
  15988. var invLocalWorldMatrix = this._localWorld.clone();
  15989. invLocalWorldMatrix.invert();
  15990. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  15991. };
  15992. /**
  15993. * Translates the mesh along the passed Vector3 in its local space.
  15994. * Returns the AbstractMesh.
  15995. */
  15996. TransformNode.prototype.locallyTranslate = function (vector3) {
  15997. this.computeWorldMatrix(true);
  15998. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  15999. return this;
  16000. };
  16001. /**
  16002. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16003. * @param targetPoint the position (must be in same space as current mesh) to look at
  16004. * @param yawCor optional yaw (y-axis) correction in radians
  16005. * @param pitchCor optional pitch (x-axis) correction in radians
  16006. * @param rollCor optional roll (z-axis) correction in radians
  16007. * @param space the choosen space of the target
  16008. * @returns the TransformNode.
  16009. */
  16010. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16011. if (yawCor === void 0) { yawCor = 0; }
  16012. if (pitchCor === void 0) { pitchCor = 0; }
  16013. if (rollCor === void 0) { rollCor = 0; }
  16014. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16015. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16016. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16017. targetPoint.subtractToRef(pos, dv);
  16018. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16019. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16020. var pitch = Math.atan2(dv.y, len);
  16021. if (this.rotationQuaternion) {
  16022. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16023. }
  16024. else {
  16025. this.rotation.x = pitch + pitchCor;
  16026. this.rotation.y = yaw + yawCor;
  16027. this.rotation.z = rollCor;
  16028. }
  16029. return this;
  16030. };
  16031. /**
  16032. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16033. * This Vector3 is expressed in the World space.
  16034. */
  16035. TransformNode.prototype.getDirection = function (localAxis) {
  16036. var result = BABYLON.Vector3.Zero();
  16037. this.getDirectionToRef(localAxis, result);
  16038. return result;
  16039. };
  16040. /**
  16041. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16042. * localAxis is expressed in the mesh local space.
  16043. * result is computed in the Wordl space from the mesh World matrix.
  16044. * Returns the AbstractMesh.
  16045. */
  16046. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16047. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16048. return this;
  16049. };
  16050. /**
  16051. * Sets a new pivot point to the current node
  16052. * @param point defines the new pivot point to use
  16053. * @param space defines if the point is in world or local space (local by default)
  16054. * @returns the current TransformNode
  16055. */
  16056. TransformNode.prototype.setPivotPoint = function (point, space) {
  16057. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16058. if (this.getScene().getRenderId() == 0) {
  16059. this.computeWorldMatrix(true);
  16060. }
  16061. var wm = this.getWorldMatrix();
  16062. if (space == BABYLON.Space.WORLD) {
  16063. var tmat = BABYLON.Tmp.Matrix[0];
  16064. wm.invertToRef(tmat);
  16065. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16066. }
  16067. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16068. };
  16069. /**
  16070. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16071. */
  16072. TransformNode.prototype.getPivotPoint = function () {
  16073. var point = BABYLON.Vector3.Zero();
  16074. this.getPivotPointToRef(point);
  16075. return point;
  16076. };
  16077. /**
  16078. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16079. * Returns the AbstractMesh.
  16080. */
  16081. TransformNode.prototype.getPivotPointToRef = function (result) {
  16082. result.x = -this._pivotMatrix.m[12];
  16083. result.y = -this._pivotMatrix.m[13];
  16084. result.z = -this._pivotMatrix.m[14];
  16085. return this;
  16086. };
  16087. /**
  16088. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16089. */
  16090. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16091. var point = BABYLON.Vector3.Zero();
  16092. this.getAbsolutePivotPointToRef(point);
  16093. return point;
  16094. };
  16095. /**
  16096. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16097. * Returns the AbstractMesh.
  16098. */
  16099. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16100. result.x = this._pivotMatrix.m[12];
  16101. result.y = this._pivotMatrix.m[13];
  16102. result.z = this._pivotMatrix.m[14];
  16103. this.getPivotPointToRef(result);
  16104. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16105. return this;
  16106. };
  16107. /**
  16108. * Defines the passed node as the parent of the current node.
  16109. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16110. * Returns the TransformNode.
  16111. */
  16112. TransformNode.prototype.setParent = function (node) {
  16113. if (node === null) {
  16114. var rotation = BABYLON.Tmp.Quaternion[0];
  16115. var position = BABYLON.Tmp.Vector3[0];
  16116. var scale = BABYLON.Tmp.Vector3[1];
  16117. if (this.parent && this.parent.computeWorldMatrix) {
  16118. this.parent.computeWorldMatrix(true);
  16119. }
  16120. this.computeWorldMatrix(true);
  16121. this.getWorldMatrix().decompose(scale, rotation, position);
  16122. if (this.rotationQuaternion) {
  16123. this.rotationQuaternion.copyFrom(rotation);
  16124. }
  16125. else {
  16126. rotation.toEulerAnglesToRef(this.rotation);
  16127. }
  16128. this.scaling.x = scale.x;
  16129. this.scaling.y = scale.y;
  16130. this.scaling.z = scale.z;
  16131. this.position.x = position.x;
  16132. this.position.y = position.y;
  16133. this.position.z = position.z;
  16134. }
  16135. else {
  16136. var rotation = BABYLON.Tmp.Quaternion[0];
  16137. var position = BABYLON.Tmp.Vector3[0];
  16138. var scale = BABYLON.Tmp.Vector3[1];
  16139. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16140. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16141. this.computeWorldMatrix(true);
  16142. node.computeWorldMatrix(true);
  16143. node.getWorldMatrix().invertToRef(invParentMatrix);
  16144. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16145. diffMatrix.decompose(scale, rotation, position);
  16146. if (this.rotationQuaternion) {
  16147. this.rotationQuaternion.copyFrom(rotation);
  16148. }
  16149. else {
  16150. rotation.toEulerAnglesToRef(this.rotation);
  16151. }
  16152. this.position.x = position.x;
  16153. this.position.y = position.y;
  16154. this.position.z = position.z;
  16155. this.scaling.x = scale.x;
  16156. this.scaling.y = scale.y;
  16157. this.scaling.z = scale.z;
  16158. }
  16159. this.parent = node;
  16160. return this;
  16161. };
  16162. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16163. get: function () {
  16164. return this._nonUniformScaling;
  16165. },
  16166. enumerable: true,
  16167. configurable: true
  16168. });
  16169. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16170. if (this._nonUniformScaling === value) {
  16171. return false;
  16172. }
  16173. this._nonUniformScaling = true;
  16174. return true;
  16175. };
  16176. /**
  16177. * Attach the current TransformNode to another TransformNode associated with a bone
  16178. * @param bone Bone affecting the TransformNode
  16179. * @param affectedTransformNode TransformNode associated with the bone
  16180. */
  16181. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16182. this._transformToBoneReferal = affectedTransformNode;
  16183. this.parent = bone;
  16184. if (bone.getWorldMatrix().determinant() < 0) {
  16185. this.scalingDeterminant *= -1;
  16186. }
  16187. return this;
  16188. };
  16189. TransformNode.prototype.detachFromBone = function () {
  16190. if (!this.parent) {
  16191. return this;
  16192. }
  16193. if (this.parent.getWorldMatrix().determinant() < 0) {
  16194. this.scalingDeterminant *= -1;
  16195. }
  16196. this._transformToBoneReferal = null;
  16197. this.parent = null;
  16198. return this;
  16199. };
  16200. /**
  16201. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16202. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16203. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16204. * The passed axis is also normalized.
  16205. * Returns the AbstractMesh.
  16206. */
  16207. TransformNode.prototype.rotate = function (axis, amount, space) {
  16208. axis.normalize();
  16209. if (!this.rotationQuaternion) {
  16210. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16211. this.rotation = BABYLON.Vector3.Zero();
  16212. }
  16213. var rotationQuaternion;
  16214. if (!space || space === BABYLON.Space.LOCAL) {
  16215. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16216. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16217. }
  16218. else {
  16219. if (this.parent) {
  16220. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16221. invertParentWorldMatrix.invert();
  16222. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16223. }
  16224. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16225. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16226. }
  16227. return this;
  16228. };
  16229. /**
  16230. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16231. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16232. * The passed axis is also normalized.
  16233. * Returns the AbstractMesh.
  16234. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16235. */
  16236. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16237. axis.normalize();
  16238. if (!this.rotationQuaternion) {
  16239. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16240. this.rotation.copyFromFloats(0, 0, 0);
  16241. }
  16242. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16243. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16244. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16245. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16246. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16247. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16248. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16249. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16250. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16251. return this;
  16252. };
  16253. /**
  16254. * Translates the mesh along the axis vector for the passed distance in the given space.
  16255. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16256. * Returns the AbstractMesh.
  16257. */
  16258. TransformNode.prototype.translate = function (axis, distance, space) {
  16259. var displacementVector = axis.scale(distance);
  16260. if (!space || space === BABYLON.Space.LOCAL) {
  16261. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16262. this.setPositionWithLocalVector(tempV3);
  16263. }
  16264. else {
  16265. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16266. }
  16267. return this;
  16268. };
  16269. /**
  16270. * Adds a rotation step to the mesh current rotation.
  16271. * x, y, z are Euler angles expressed in radians.
  16272. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16273. * This means this rotation is made in the mesh local space only.
  16274. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16275. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16276. * ```javascript
  16277. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16278. * ```
  16279. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16280. * 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.
  16281. * Returns the AbstractMesh.
  16282. */
  16283. TransformNode.prototype.addRotation = function (x, y, z) {
  16284. var rotationQuaternion;
  16285. if (this.rotationQuaternion) {
  16286. rotationQuaternion = this.rotationQuaternion;
  16287. }
  16288. else {
  16289. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16290. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16291. }
  16292. var accumulation = BABYLON.Tmp.Quaternion[0];
  16293. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16294. rotationQuaternion.multiplyInPlace(accumulation);
  16295. if (!this.rotationQuaternion) {
  16296. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16297. }
  16298. return this;
  16299. };
  16300. /**
  16301. * Computes the mesh World matrix and returns it.
  16302. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16303. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16304. * If the parameter `force`is set to `true`, the actual computation is done.
  16305. * Returns the mesh World Matrix.
  16306. */
  16307. TransformNode.prototype.computeWorldMatrix = function (force) {
  16308. if (this._isWorldMatrixFrozen) {
  16309. return this._worldMatrix;
  16310. }
  16311. if (!force && this.isSynchronized(true)) {
  16312. return this._worldMatrix;
  16313. }
  16314. this._cache.position.copyFrom(this.position);
  16315. this._cache.scaling.copyFrom(this.scaling);
  16316. this._cache.pivotMatrixUpdated = false;
  16317. this._cache.billboardMode = this.billboardMode;
  16318. this._currentRenderId = this.getScene().getRenderId();
  16319. this._isDirty = false;
  16320. // Scaling
  16321. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16322. // Rotation
  16323. //rotate, if quaternion is set and rotation was used
  16324. if (this.rotationQuaternion) {
  16325. var len = this.rotation.length();
  16326. if (len) {
  16327. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16328. this.rotation.copyFromFloats(0, 0, 0);
  16329. }
  16330. }
  16331. if (this.rotationQuaternion) {
  16332. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16333. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16334. }
  16335. else {
  16336. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16337. this._cache.rotation.copyFrom(this.rotation);
  16338. }
  16339. // Translation
  16340. var camera = this.getScene().activeCamera;
  16341. if (this.infiniteDistance && !this.parent && camera) {
  16342. var cameraWorldMatrix = camera.getWorldMatrix();
  16343. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16344. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16345. }
  16346. else {
  16347. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16348. }
  16349. // Composing transformations
  16350. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16351. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16352. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16353. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16354. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16355. // Need to decompose each rotation here
  16356. var currentPosition = BABYLON.Tmp.Vector3[3];
  16357. if (this.parent && this.parent.getWorldMatrix) {
  16358. if (this._transformToBoneReferal) {
  16359. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16360. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16361. }
  16362. else {
  16363. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16364. }
  16365. }
  16366. else {
  16367. currentPosition.copyFrom(this.position);
  16368. }
  16369. currentPosition.subtractInPlace(camera.globalPosition);
  16370. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16371. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16372. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16373. }
  16374. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16375. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16376. }
  16377. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16378. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16379. }
  16380. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16381. }
  16382. else {
  16383. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16384. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16385. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16386. }
  16387. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16388. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16389. }
  16390. // Local world
  16391. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16392. // Parent
  16393. if (this.parent && this.parent.getWorldMatrix) {
  16394. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16395. if (this._transformToBoneReferal) {
  16396. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16397. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16398. }
  16399. else {
  16400. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16401. }
  16402. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16403. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16404. this._worldMatrix.copyFrom(this._localWorld);
  16405. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16406. }
  16407. else {
  16408. if (this._transformToBoneReferal) {
  16409. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16410. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16411. }
  16412. else {
  16413. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16414. }
  16415. }
  16416. this._markSyncedWithParent();
  16417. }
  16418. else {
  16419. this._worldMatrix.copyFrom(this._localWorld);
  16420. }
  16421. // Post multiply inverse of pivotMatrix
  16422. if (this._postMultiplyPivotMatrix) {
  16423. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16424. }
  16425. // Normal matrix
  16426. if (this.scaling.isNonUniform) {
  16427. this._updateNonUniformScalingState(true);
  16428. }
  16429. else if (this.parent && this.parent._nonUniformScaling) {
  16430. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16431. }
  16432. else {
  16433. this._updateNonUniformScalingState(false);
  16434. }
  16435. this._afterComputeWorldMatrix();
  16436. // Absolute position
  16437. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16438. // Callbacks
  16439. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16440. if (!this._poseMatrix) {
  16441. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16442. }
  16443. // Cache the determinant
  16444. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16445. return this._worldMatrix;
  16446. };
  16447. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16448. };
  16449. /**
  16450. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16451. * @param func: callback function to add
  16452. *
  16453. * Returns the TransformNode.
  16454. */
  16455. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16456. this.onAfterWorldMatrixUpdateObservable.add(func);
  16457. return this;
  16458. };
  16459. /**
  16460. * Removes a registered callback function.
  16461. * Returns the TransformNode.
  16462. */
  16463. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16464. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16465. return this;
  16466. };
  16467. /**
  16468. * Clone the current transform node
  16469. * Returns the new transform node
  16470. * @param name Name of the new clone
  16471. * @param newParent New parent for the clone
  16472. * @param doNotCloneChildren Do not clone children hierarchy
  16473. */
  16474. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16475. var _this = this;
  16476. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16477. result.name = name;
  16478. result.id = name;
  16479. if (newParent) {
  16480. result.parent = newParent;
  16481. }
  16482. if (!doNotCloneChildren) {
  16483. // Children
  16484. var directDescendants = this.getDescendants(true);
  16485. for (var index = 0; index < directDescendants.length; index++) {
  16486. var child = directDescendants[index];
  16487. if (child.clone) {
  16488. child.clone(name + "." + child.name, result);
  16489. }
  16490. }
  16491. }
  16492. return result;
  16493. };
  16494. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16495. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16496. serializationObject.type = this.getClassName();
  16497. // Parent
  16498. if (this.parent) {
  16499. serializationObject.parentId = this.parent.id;
  16500. }
  16501. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16502. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16503. }
  16504. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16505. serializationObject.isEnabled = this.isEnabled();
  16506. // Parent
  16507. if (this.parent) {
  16508. serializationObject.parentId = this.parent.id;
  16509. }
  16510. return serializationObject;
  16511. };
  16512. // Statics
  16513. /**
  16514. * Returns a new TransformNode object parsed from the source provided.
  16515. * The parameter `parsedMesh` is the source.
  16516. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16517. */
  16518. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16519. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16520. if (BABYLON.Tags) {
  16521. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16522. }
  16523. if (parsedTransformNode.localMatrix) {
  16524. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16525. }
  16526. else if (parsedTransformNode.pivotMatrix) {
  16527. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16528. }
  16529. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16530. // Parent
  16531. if (parsedTransformNode.parentId) {
  16532. transformNode._waitingParentId = parsedTransformNode.parentId;
  16533. }
  16534. return transformNode;
  16535. };
  16536. /**
  16537. * Disposes the TransformNode.
  16538. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16539. * Returns nothing.
  16540. */
  16541. TransformNode.prototype.dispose = function (doNotRecurse) {
  16542. // Animations
  16543. this.getScene().stopAnimation(this);
  16544. // Remove from scene
  16545. this.getScene().removeTransformNode(this);
  16546. if (!doNotRecurse) {
  16547. // Children
  16548. var objects = this.getDescendants(true);
  16549. for (var index = 0; index < objects.length; index++) {
  16550. objects[index].dispose();
  16551. }
  16552. }
  16553. else {
  16554. var childMeshes = this.getChildMeshes(true);
  16555. for (index = 0; index < childMeshes.length; index++) {
  16556. var child = childMeshes[index];
  16557. child.parent = null;
  16558. child.computeWorldMatrix(true);
  16559. }
  16560. }
  16561. this.onAfterWorldMatrixUpdateObservable.clear();
  16562. _super.prototype.dispose.call(this);
  16563. };
  16564. // Statics
  16565. TransformNode.BILLBOARDMODE_NONE = 0;
  16566. TransformNode.BILLBOARDMODE_X = 1;
  16567. TransformNode.BILLBOARDMODE_Y = 2;
  16568. TransformNode.BILLBOARDMODE_Z = 4;
  16569. TransformNode.BILLBOARDMODE_ALL = 7;
  16570. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16571. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16572. __decorate([
  16573. BABYLON.serializeAsVector3()
  16574. ], TransformNode.prototype, "_rotation", void 0);
  16575. __decorate([
  16576. BABYLON.serializeAsQuaternion()
  16577. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16578. __decorate([
  16579. BABYLON.serializeAsVector3()
  16580. ], TransformNode.prototype, "_scaling", void 0);
  16581. __decorate([
  16582. BABYLON.serialize()
  16583. ], TransformNode.prototype, "billboardMode", void 0);
  16584. __decorate([
  16585. BABYLON.serialize()
  16586. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16587. __decorate([
  16588. BABYLON.serialize()
  16589. ], TransformNode.prototype, "infiniteDistance", void 0);
  16590. __decorate([
  16591. BABYLON.serializeAsVector3()
  16592. ], TransformNode.prototype, "position", void 0);
  16593. return TransformNode;
  16594. }(BABYLON.Node));
  16595. BABYLON.TransformNode = TransformNode;
  16596. })(BABYLON || (BABYLON = {}));
  16597. //# sourceMappingURL=babylon.transformNode.js.map
  16598. var BABYLON;
  16599. (function (BABYLON) {
  16600. var AbstractMesh = /** @class */ (function (_super) {
  16601. __extends(AbstractMesh, _super);
  16602. // Constructor
  16603. function AbstractMesh(name, scene) {
  16604. if (scene === void 0) { scene = null; }
  16605. var _this = _super.call(this, name, scene, false) || this;
  16606. _this._facetNb = 0; // facet number
  16607. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16608. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16609. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16610. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16611. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16612. _this._subDiv = {
  16613. max: 1,
  16614. X: 1,
  16615. Y: 1,
  16616. Z: 1
  16617. };
  16618. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16619. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16620. // Events
  16621. /**
  16622. * An event triggered when this mesh collides with another one
  16623. * @type {BABYLON.Observable}
  16624. */
  16625. _this.onCollideObservable = new BABYLON.Observable();
  16626. /**
  16627. * An event triggered when the collision's position changes
  16628. * @type {BABYLON.Observable}
  16629. */
  16630. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16631. /**
  16632. * An event triggered when material is changed
  16633. * @type {BABYLON.Observable}
  16634. */
  16635. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16636. // Properties
  16637. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16638. /**
  16639. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16640. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16641. * or
  16642. * 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.
  16643. * for more info check WebGl documentations
  16644. */
  16645. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16646. /**
  16647. * 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:
  16648. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16649. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16650. * 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.
  16651. */
  16652. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16653. /**
  16654. * 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.
  16655. * The default value is -1 which means don't break the query and wait till the result.
  16656. */
  16657. _this.occlusionRetryCount = -1;
  16658. _this._occlusionInternalRetryCounter = 0;
  16659. _this._isOccluded = false;
  16660. _this._isOcclusionQueryInProgress = false;
  16661. _this._visibility = 1.0;
  16662. _this.alphaIndex = Number.MAX_VALUE;
  16663. _this.isVisible = true;
  16664. _this.isPickable = true;
  16665. _this.showBoundingBox = false;
  16666. _this.showSubMeshesBoundingBox = false;
  16667. _this.isBlocker = false;
  16668. _this.enablePointerMoveEvents = false;
  16669. _this.renderingGroupId = 0;
  16670. _this._receiveShadows = false;
  16671. _this.renderOutline = false;
  16672. _this.outlineColor = BABYLON.Color3.Red();
  16673. _this.outlineWidth = 0.02;
  16674. _this.renderOverlay = false;
  16675. _this.overlayColor = BABYLON.Color3.Red();
  16676. _this.overlayAlpha = 0.5;
  16677. _this._hasVertexAlpha = false;
  16678. _this._useVertexColors = true;
  16679. _this._computeBonesUsingShaders = true;
  16680. _this._numBoneInfluencers = 4;
  16681. _this._applyFog = true;
  16682. _this.useOctreeForRenderingSelection = true;
  16683. _this.useOctreeForPicking = true;
  16684. _this.useOctreeForCollisions = true;
  16685. _this._layerMask = 0x0FFFFFFF;
  16686. /**
  16687. * True if the mesh must be rendered in any case.
  16688. */
  16689. _this.alwaysSelectAsActiveMesh = false;
  16690. /**
  16691. * This scene's action manager
  16692. * @type {BABYLON.ActionManager}
  16693. */
  16694. _this.actionManager = null;
  16695. // Physics
  16696. _this.physicsImpostor = null;
  16697. // Collisions
  16698. _this._checkCollisions = false;
  16699. _this._collisionMask = -1;
  16700. _this._collisionGroup = -1;
  16701. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16702. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16703. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16704. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16705. // Edges
  16706. _this.edgesWidth = 1;
  16707. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16708. // Cache
  16709. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16710. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16711. _this._isDisposed = false;
  16712. _this._renderId = 0;
  16713. _this._intersectionsInProgress = new Array();
  16714. _this._unIndexed = false;
  16715. _this._lightSources = new Array();
  16716. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16717. if (collidedMesh === void 0) { collidedMesh = null; }
  16718. //TODO move this to the collision coordinator!
  16719. if (_this.getScene().workerCollisions)
  16720. newPosition.multiplyInPlace(_this._collider._radius);
  16721. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16722. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16723. _this.position.addInPlace(_this._diffPositionForCollisions);
  16724. }
  16725. if (collidedMesh) {
  16726. _this.onCollideObservable.notifyObservers(collidedMesh);
  16727. }
  16728. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16729. };
  16730. _this.getScene().addMesh(_this);
  16731. _this._resyncLightSources();
  16732. return _this;
  16733. }
  16734. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16735. get: function () {
  16736. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16737. },
  16738. enumerable: true,
  16739. configurable: true
  16740. });
  16741. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16742. get: function () {
  16743. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16744. },
  16745. enumerable: true,
  16746. configurable: true
  16747. });
  16748. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16749. get: function () {
  16750. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16751. },
  16752. enumerable: true,
  16753. configurable: true
  16754. });
  16755. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16756. get: function () {
  16757. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16758. },
  16759. enumerable: true,
  16760. configurable: true
  16761. });
  16762. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16763. get: function () {
  16764. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16765. },
  16766. enumerable: true,
  16767. configurable: true
  16768. });
  16769. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  16770. /**
  16771. * Read-only : the number of facets in the mesh
  16772. */
  16773. get: function () {
  16774. return this._facetNb;
  16775. },
  16776. enumerable: true,
  16777. configurable: true
  16778. });
  16779. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16780. /**
  16781. * The number (integer) of subdivisions per axis in the partioning space
  16782. */
  16783. get: function () {
  16784. return this._partitioningSubdivisions;
  16785. },
  16786. set: function (nb) {
  16787. this._partitioningSubdivisions = nb;
  16788. },
  16789. enumerable: true,
  16790. configurable: true
  16791. });
  16792. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16793. /**
  16794. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16795. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16796. */
  16797. get: function () {
  16798. return this._partitioningBBoxRatio;
  16799. },
  16800. set: function (ratio) {
  16801. this._partitioningBBoxRatio = ratio;
  16802. },
  16803. enumerable: true,
  16804. configurable: true
  16805. });
  16806. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16807. /**
  16808. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16809. * Works only for updatable meshes.
  16810. * Doesn't work with multi-materials.
  16811. */
  16812. get: function () {
  16813. return this._facetDepthSort;
  16814. },
  16815. set: function (sort) {
  16816. this._facetDepthSort = sort;
  16817. },
  16818. enumerable: true,
  16819. configurable: true
  16820. });
  16821. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16822. /**
  16823. * The location (Vector3) where the facet depth sort must be computed from.
  16824. * By default, the active camera position.
  16825. * Used only when facet depth sort is enabled.
  16826. */
  16827. get: function () {
  16828. return this._facetDepthSortFrom;
  16829. },
  16830. set: function (location) {
  16831. this._facetDepthSortFrom = location;
  16832. },
  16833. enumerable: true,
  16834. configurable: true
  16835. });
  16836. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16837. /**
  16838. * Read-only boolean : is the feature facetData enabled ?
  16839. */
  16840. get: function () {
  16841. return this._facetDataEnabled;
  16842. },
  16843. enumerable: true,
  16844. configurable: true
  16845. });
  16846. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16847. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16848. return false;
  16849. }
  16850. this._markSubMeshesAsMiscDirty();
  16851. return true;
  16852. };
  16853. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16854. set: function (callback) {
  16855. if (this._onCollideObserver) {
  16856. this.onCollideObservable.remove(this._onCollideObserver);
  16857. }
  16858. this._onCollideObserver = this.onCollideObservable.add(callback);
  16859. },
  16860. enumerable: true,
  16861. configurable: true
  16862. });
  16863. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16864. set: function (callback) {
  16865. if (this._onCollisionPositionChangeObserver) {
  16866. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16867. }
  16868. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16869. },
  16870. enumerable: true,
  16871. configurable: true
  16872. });
  16873. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16874. /**
  16875. * Property isOccluded : 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.
  16876. */
  16877. get: function () {
  16878. return this._isOccluded;
  16879. },
  16880. set: function (value) {
  16881. this._isOccluded = value;
  16882. },
  16883. enumerable: true,
  16884. configurable: true
  16885. });
  16886. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  16887. /**
  16888. * Flag to check the progress status of the query
  16889. */
  16890. get: function () {
  16891. return this._isOcclusionQueryInProgress;
  16892. },
  16893. enumerable: true,
  16894. configurable: true
  16895. });
  16896. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  16897. /**
  16898. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16899. */
  16900. get: function () {
  16901. return this._visibility;
  16902. },
  16903. /**
  16904. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16905. */
  16906. set: function (value) {
  16907. if (this._visibility === value) {
  16908. return;
  16909. }
  16910. this._visibility = value;
  16911. this._markSubMeshesAsMiscDirty();
  16912. },
  16913. enumerable: true,
  16914. configurable: true
  16915. });
  16916. Object.defineProperty(AbstractMesh.prototype, "material", {
  16917. get: function () {
  16918. return this._material;
  16919. },
  16920. set: function (value) {
  16921. if (this._material === value) {
  16922. return;
  16923. }
  16924. this._material = value;
  16925. if (this.onMaterialChangedObservable.hasObservers) {
  16926. this.onMaterialChangedObservable.notifyObservers(this);
  16927. }
  16928. if (!this.subMeshes) {
  16929. return;
  16930. }
  16931. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16932. var subMesh = _a[_i];
  16933. subMesh.setEffect(null);
  16934. }
  16935. },
  16936. enumerable: true,
  16937. configurable: true
  16938. });
  16939. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  16940. get: function () {
  16941. return this._receiveShadows;
  16942. },
  16943. set: function (value) {
  16944. if (this._receiveShadows === value) {
  16945. return;
  16946. }
  16947. this._receiveShadows = value;
  16948. this._markSubMeshesAsLightDirty();
  16949. },
  16950. enumerable: true,
  16951. configurable: true
  16952. });
  16953. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  16954. get: function () {
  16955. return this._hasVertexAlpha;
  16956. },
  16957. set: function (value) {
  16958. if (this._hasVertexAlpha === value) {
  16959. return;
  16960. }
  16961. this._hasVertexAlpha = value;
  16962. this._markSubMeshesAsAttributesDirty();
  16963. this._markSubMeshesAsMiscDirty();
  16964. },
  16965. enumerable: true,
  16966. configurable: true
  16967. });
  16968. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  16969. get: function () {
  16970. return this._useVertexColors;
  16971. },
  16972. set: function (value) {
  16973. if (this._useVertexColors === value) {
  16974. return;
  16975. }
  16976. this._useVertexColors = value;
  16977. this._markSubMeshesAsAttributesDirty();
  16978. },
  16979. enumerable: true,
  16980. configurable: true
  16981. });
  16982. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  16983. get: function () {
  16984. return this._computeBonesUsingShaders;
  16985. },
  16986. set: function (value) {
  16987. if (this._computeBonesUsingShaders === value) {
  16988. return;
  16989. }
  16990. this._computeBonesUsingShaders = value;
  16991. this._markSubMeshesAsAttributesDirty();
  16992. },
  16993. enumerable: true,
  16994. configurable: true
  16995. });
  16996. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  16997. get: function () {
  16998. return this._numBoneInfluencers;
  16999. },
  17000. set: function (value) {
  17001. if (this._numBoneInfluencers === value) {
  17002. return;
  17003. }
  17004. this._numBoneInfluencers = value;
  17005. this._markSubMeshesAsAttributesDirty();
  17006. },
  17007. enumerable: true,
  17008. configurable: true
  17009. });
  17010. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17011. get: function () {
  17012. return this._applyFog;
  17013. },
  17014. set: function (value) {
  17015. if (this._applyFog === value) {
  17016. return;
  17017. }
  17018. this._applyFog = value;
  17019. this._markSubMeshesAsMiscDirty();
  17020. },
  17021. enumerable: true,
  17022. configurable: true
  17023. });
  17024. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17025. get: function () {
  17026. return this._layerMask;
  17027. },
  17028. set: function (value) {
  17029. if (value === this._layerMask) {
  17030. return;
  17031. }
  17032. this._layerMask = value;
  17033. this._resyncLightSources();
  17034. },
  17035. enumerable: true,
  17036. configurable: true
  17037. });
  17038. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17039. get: function () {
  17040. return this._collisionMask;
  17041. },
  17042. set: function (mask) {
  17043. this._collisionMask = !isNaN(mask) ? mask : -1;
  17044. },
  17045. enumerable: true,
  17046. configurable: true
  17047. });
  17048. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17049. get: function () {
  17050. return this._collisionGroup;
  17051. },
  17052. set: function (mask) {
  17053. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17054. },
  17055. enumerable: true,
  17056. configurable: true
  17057. });
  17058. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17059. get: function () {
  17060. return null;
  17061. },
  17062. enumerable: true,
  17063. configurable: true
  17064. });
  17065. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17066. get: function () {
  17067. return this._skeleton;
  17068. },
  17069. set: function (value) {
  17070. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17071. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17072. }
  17073. if (value && value.needInitialSkinMatrix) {
  17074. value._registerMeshWithPoseMatrix(this);
  17075. }
  17076. this._skeleton = value;
  17077. if (!this._skeleton) {
  17078. this._bonesTransformMatrices = null;
  17079. }
  17080. this._markSubMeshesAsAttributesDirty();
  17081. },
  17082. enumerable: true,
  17083. configurable: true
  17084. });
  17085. /**
  17086. * Boolean : true if the mesh has been disposed.
  17087. */
  17088. AbstractMesh.prototype.isDisposed = function () {
  17089. return this._isDisposed;
  17090. };
  17091. /**
  17092. * Returns the string "AbstractMesh"
  17093. */
  17094. AbstractMesh.prototype.getClassName = function () {
  17095. return "AbstractMesh";
  17096. };
  17097. /**
  17098. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17099. */
  17100. AbstractMesh.prototype.toString = function (fullDetails) {
  17101. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17102. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17103. if (this._skeleton) {
  17104. ret += ", skeleton: " + this._skeleton.name;
  17105. }
  17106. if (fullDetails) {
  17107. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17108. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17109. }
  17110. return ret;
  17111. };
  17112. AbstractMesh.prototype._rebuild = function () {
  17113. if (this._occlusionQuery) {
  17114. this._occlusionQuery = null;
  17115. }
  17116. if (this._edgesRenderer) {
  17117. this._edgesRenderer._rebuild();
  17118. }
  17119. if (!this.subMeshes) {
  17120. return;
  17121. }
  17122. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17123. var subMesh = _a[_i];
  17124. subMesh._rebuild();
  17125. }
  17126. };
  17127. AbstractMesh.prototype._resyncLightSources = function () {
  17128. this._lightSources.length = 0;
  17129. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17130. var light = _a[_i];
  17131. if (!light.isEnabled()) {
  17132. continue;
  17133. }
  17134. if (light.canAffectMesh(this)) {
  17135. this._lightSources.push(light);
  17136. }
  17137. }
  17138. this._markSubMeshesAsLightDirty();
  17139. };
  17140. AbstractMesh.prototype._resyncLighSource = function (light) {
  17141. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17142. var index = this._lightSources.indexOf(light);
  17143. if (index === -1) {
  17144. if (!isIn) {
  17145. return;
  17146. }
  17147. this._lightSources.push(light);
  17148. }
  17149. else {
  17150. if (isIn) {
  17151. return;
  17152. }
  17153. this._lightSources.splice(index, 1);
  17154. }
  17155. this._markSubMeshesAsLightDirty();
  17156. };
  17157. AbstractMesh.prototype._removeLightSource = function (light) {
  17158. var index = this._lightSources.indexOf(light);
  17159. if (index === -1) {
  17160. return;
  17161. }
  17162. this._lightSources.splice(index, 1);
  17163. this._markSubMeshesAsLightDirty();
  17164. };
  17165. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17166. if (!this.subMeshes) {
  17167. return;
  17168. }
  17169. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17170. var subMesh = _a[_i];
  17171. if (subMesh._materialDefines) {
  17172. func(subMesh._materialDefines);
  17173. }
  17174. }
  17175. };
  17176. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17177. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17178. };
  17179. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17180. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17181. };
  17182. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17183. if (!this.subMeshes) {
  17184. return;
  17185. }
  17186. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17187. var subMesh = _a[_i];
  17188. var material = subMesh.getMaterial();
  17189. if (material) {
  17190. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17191. }
  17192. }
  17193. };
  17194. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17195. /**
  17196. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17197. * Default : (1.0, 1.0, 1.0)
  17198. */
  17199. get: function () {
  17200. return this._scaling;
  17201. },
  17202. /**
  17203. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17204. * Default : (1.0, 1.0, 1.0)
  17205. */
  17206. set: function (newScaling) {
  17207. this._scaling = newScaling;
  17208. if (this.physicsImpostor) {
  17209. this.physicsImpostor.forceUpdate();
  17210. }
  17211. },
  17212. enumerable: true,
  17213. configurable: true
  17214. });
  17215. // Methods
  17216. /**
  17217. * Disables the mesh edger rendering mode.
  17218. * Returns the AbstractMesh.
  17219. */
  17220. AbstractMesh.prototype.disableEdgesRendering = function () {
  17221. if (this._edgesRenderer) {
  17222. this._edgesRenderer.dispose();
  17223. this._edgesRenderer = null;
  17224. }
  17225. return this;
  17226. };
  17227. /**
  17228. * Enables the edge rendering mode on the mesh.
  17229. * This mode makes the mesh edges visible.
  17230. * Returns the AbstractMesh.
  17231. */
  17232. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17233. if (epsilon === void 0) { epsilon = 0.95; }
  17234. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17235. this.disableEdgesRendering();
  17236. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17237. return this;
  17238. };
  17239. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17240. /**
  17241. * Returns true if the mesh is blocked. Used by the class Mesh.
  17242. * Returns the boolean `false` by default.
  17243. */
  17244. get: function () {
  17245. return false;
  17246. },
  17247. enumerable: true,
  17248. configurable: true
  17249. });
  17250. /**
  17251. * Returns the mesh itself by default, used by the class Mesh.
  17252. * Returned type : AbstractMesh
  17253. */
  17254. AbstractMesh.prototype.getLOD = function (camera) {
  17255. return this;
  17256. };
  17257. /**
  17258. * Returns 0 by default, used by the class Mesh.
  17259. * Returns an integer.
  17260. */
  17261. AbstractMesh.prototype.getTotalVertices = function () {
  17262. return 0;
  17263. };
  17264. /**
  17265. * Returns null by default, used by the class Mesh.
  17266. * Returned type : integer array
  17267. */
  17268. AbstractMesh.prototype.getIndices = function () {
  17269. return null;
  17270. };
  17271. /**
  17272. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17273. * Returned type : float array or Float32Array
  17274. */
  17275. AbstractMesh.prototype.getVerticesData = function (kind) {
  17276. return null;
  17277. };
  17278. /**
  17279. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17280. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17281. * The `data` are either a numeric array either a Float32Array.
  17282. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17283. * 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).
  17284. * Note that a new underlying VertexBuffer object is created each call.
  17285. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17286. *
  17287. * Possible `kind` values :
  17288. * - BABYLON.VertexBuffer.PositionKind
  17289. * - BABYLON.VertexBuffer.UVKind
  17290. * - BABYLON.VertexBuffer.UV2Kind
  17291. * - BABYLON.VertexBuffer.UV3Kind
  17292. * - BABYLON.VertexBuffer.UV4Kind
  17293. * - BABYLON.VertexBuffer.UV5Kind
  17294. * - BABYLON.VertexBuffer.UV6Kind
  17295. * - BABYLON.VertexBuffer.ColorKind
  17296. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17297. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17298. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17299. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17300. *
  17301. * Returns the Mesh.
  17302. */
  17303. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17304. return this;
  17305. };
  17306. /**
  17307. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17308. * If the mesh has no geometry, it is simply returned as it is.
  17309. * The `data` are either a numeric array either a Float32Array.
  17310. * No new underlying VertexBuffer object is created.
  17311. * 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.
  17312. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17313. *
  17314. * Possible `kind` values :
  17315. * - BABYLON.VertexBuffer.PositionKind
  17316. * - BABYLON.VertexBuffer.UVKind
  17317. * - BABYLON.VertexBuffer.UV2Kind
  17318. * - BABYLON.VertexBuffer.UV3Kind
  17319. * - BABYLON.VertexBuffer.UV4Kind
  17320. * - BABYLON.VertexBuffer.UV5Kind
  17321. * - BABYLON.VertexBuffer.UV6Kind
  17322. * - BABYLON.VertexBuffer.ColorKind
  17323. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17324. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17325. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17326. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17327. *
  17328. * Returns the Mesh.
  17329. */
  17330. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17331. return this;
  17332. };
  17333. /**
  17334. * Sets the mesh indices.
  17335. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17336. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17337. * This method creates a new index buffer each call.
  17338. * Returns the Mesh.
  17339. */
  17340. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17341. return this;
  17342. };
  17343. /** Returns false by default, used by the class Mesh.
  17344. * Returns a boolean
  17345. */
  17346. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17347. return false;
  17348. };
  17349. /**
  17350. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17351. * Returns a BoundingInfo
  17352. */
  17353. AbstractMesh.prototype.getBoundingInfo = function () {
  17354. if (this._masterMesh) {
  17355. return this._masterMesh.getBoundingInfo();
  17356. }
  17357. if (!this._boundingInfo) {
  17358. // this._boundingInfo is being created here
  17359. this._updateBoundingInfo();
  17360. }
  17361. // cannot be null.
  17362. return this._boundingInfo;
  17363. };
  17364. /**
  17365. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17366. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17367. */
  17368. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17369. if (includeDescendants === void 0) { includeDescendants = true; }
  17370. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17371. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17372. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17373. if (maxDimension === 0) {
  17374. return this;
  17375. }
  17376. var scale = 1 / maxDimension;
  17377. this.scaling.scaleInPlace(scale);
  17378. return this;
  17379. };
  17380. /**
  17381. * Sets a mesh new object BoundingInfo.
  17382. * Returns the AbstractMesh.
  17383. */
  17384. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17385. this._boundingInfo = boundingInfo;
  17386. return this;
  17387. };
  17388. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17389. get: function () {
  17390. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17391. },
  17392. enumerable: true,
  17393. configurable: true
  17394. });
  17395. AbstractMesh.prototype._preActivate = function () {
  17396. };
  17397. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17398. };
  17399. AbstractMesh.prototype._activate = function (renderId) {
  17400. this._renderId = renderId;
  17401. };
  17402. /**
  17403. * Returns the latest update of the World matrix
  17404. * Returns a Matrix.
  17405. */
  17406. AbstractMesh.prototype.getWorldMatrix = function () {
  17407. if (this._masterMesh) {
  17408. return this._masterMesh.getWorldMatrix();
  17409. }
  17410. return _super.prototype.getWorldMatrix.call(this);
  17411. };
  17412. /**
  17413. * Returns the latest update of the World matrix determinant.
  17414. */
  17415. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17416. if (this._masterMesh) {
  17417. return this._masterMesh._getWorldMatrixDeterminant();
  17418. }
  17419. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17420. };
  17421. // ================================== Point of View Movement =================================
  17422. /**
  17423. * Perform relative position change from the point of view of behind the front of the mesh.
  17424. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17425. * Supports definition of mesh facing forward or backward.
  17426. * @param {number} amountRight
  17427. * @param {number} amountUp
  17428. * @param {number} amountForward
  17429. *
  17430. * Returns the AbstractMesh.
  17431. */
  17432. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17433. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17434. return this;
  17435. };
  17436. /**
  17437. * Calculate relative position change from the point of view of behind the front of the mesh.
  17438. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17439. * Supports definition of mesh facing forward or backward.
  17440. * @param {number} amountRight
  17441. * @param {number} amountUp
  17442. * @param {number} amountForward
  17443. *
  17444. * Returns a new Vector3.
  17445. */
  17446. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17447. var rotMatrix = new BABYLON.Matrix();
  17448. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17449. rotQuaternion.toRotationMatrix(rotMatrix);
  17450. var translationDelta = BABYLON.Vector3.Zero();
  17451. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17452. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17453. return translationDelta;
  17454. };
  17455. // ================================== Point of View Rotation =================================
  17456. /**
  17457. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17458. * Supports definition of mesh facing forward or backward.
  17459. * @param {number} flipBack
  17460. * @param {number} twirlClockwise
  17461. * @param {number} tiltRight
  17462. *
  17463. * Returns the AbstractMesh.
  17464. */
  17465. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17466. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17467. return this;
  17468. };
  17469. /**
  17470. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17471. * Supports definition of mesh facing forward or backward.
  17472. * @param {number} flipBack
  17473. * @param {number} twirlClockwise
  17474. * @param {number} tiltRight
  17475. *
  17476. * Returns a new Vector3.
  17477. */
  17478. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17479. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17480. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17481. };
  17482. /**
  17483. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17484. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17485. */
  17486. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17487. if (includeDescendants === void 0) { includeDescendants = true; }
  17488. this.computeWorldMatrix(true);
  17489. var min;
  17490. var max;
  17491. var boundingInfo = this.getBoundingInfo();
  17492. if (!this.subMeshes) {
  17493. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17494. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17495. }
  17496. else {
  17497. min = boundingInfo.boundingBox.minimumWorld;
  17498. max = boundingInfo.boundingBox.maximumWorld;
  17499. }
  17500. if (includeDescendants) {
  17501. var descendants = this.getDescendants(false);
  17502. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17503. var descendant = descendants_1[_i];
  17504. var childMesh = descendant;
  17505. childMesh.computeWorldMatrix(true);
  17506. //make sure we have the needed params to get mix and max
  17507. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17508. continue;
  17509. }
  17510. var childBoundingInfo = childMesh.getBoundingInfo();
  17511. var boundingBox = childBoundingInfo.boundingBox;
  17512. var minBox = boundingBox.minimumWorld;
  17513. var maxBox = boundingBox.maximumWorld;
  17514. BABYLON.Tools.CheckExtends(minBox, min, max);
  17515. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17516. }
  17517. }
  17518. return {
  17519. min: min,
  17520. max: max
  17521. };
  17522. };
  17523. /**
  17524. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17525. * Returns the AbstractMesh.
  17526. */
  17527. AbstractMesh.prototype._updateBoundingInfo = function () {
  17528. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17529. this._boundingInfo.update(this.worldMatrixFromCache);
  17530. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17531. return this;
  17532. };
  17533. /**
  17534. * Update a mesh's children BoundingInfo objects only.
  17535. * Returns the AbstractMesh.
  17536. */
  17537. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17538. if (!this.subMeshes) {
  17539. return this;
  17540. }
  17541. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17542. var subMesh = this.subMeshes[subIndex];
  17543. if (!subMesh.IsGlobal) {
  17544. subMesh.updateBoundingInfo(matrix);
  17545. }
  17546. }
  17547. return this;
  17548. };
  17549. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17550. // Bounding info
  17551. this._updateBoundingInfo();
  17552. };
  17553. /**
  17554. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17555. * A mesh is in the frustum if its bounding box intersects the frustum.
  17556. * Boolean returned.
  17557. */
  17558. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17559. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17560. };
  17561. /**
  17562. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17563. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17564. * Boolean returned.
  17565. */
  17566. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17567. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17568. ;
  17569. };
  17570. /**
  17571. * True if the mesh intersects another mesh or a SolidParticle object.
  17572. * 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)
  17573. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17574. * Returns a boolean.
  17575. */
  17576. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17577. if (precise === void 0) { precise = false; }
  17578. if (!this._boundingInfo || !mesh._boundingInfo) {
  17579. return false;
  17580. }
  17581. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17582. return true;
  17583. }
  17584. if (includeDescendants) {
  17585. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17586. var child = _a[_i];
  17587. if (child.intersectsMesh(mesh, precise, true)) {
  17588. return true;
  17589. }
  17590. }
  17591. }
  17592. return false;
  17593. };
  17594. /**
  17595. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17596. * Returns a boolean.
  17597. */
  17598. AbstractMesh.prototype.intersectsPoint = function (point) {
  17599. if (!this._boundingInfo) {
  17600. return false;
  17601. }
  17602. return this._boundingInfo.intersectsPoint(point);
  17603. };
  17604. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17605. return this.physicsImpostor;
  17606. };
  17607. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17608. if (camera === void 0) { camera = null; }
  17609. if (!camera) {
  17610. camera = this.getScene().activeCamera;
  17611. }
  17612. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17613. };
  17614. /**
  17615. * Returns the distance from the mesh to the active camera.
  17616. * Returns a float.
  17617. */
  17618. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17619. if (camera === void 0) { camera = null; }
  17620. if (!camera) {
  17621. camera = this.getScene().activeCamera;
  17622. }
  17623. return this.absolutePosition.subtract(camera.position).length();
  17624. };
  17625. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17626. if (!this.physicsImpostor) {
  17627. return this;
  17628. }
  17629. this.physicsImpostor.applyImpulse(force, contactPoint);
  17630. return this;
  17631. };
  17632. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17633. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17634. return this;
  17635. }
  17636. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17637. mainPivot: pivot1,
  17638. connectedPivot: pivot2,
  17639. nativeParams: options
  17640. });
  17641. return this;
  17642. };
  17643. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17644. // Collisions
  17645. /**
  17646. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17647. * Default `false`.
  17648. */
  17649. get: function () {
  17650. return this._checkCollisions;
  17651. },
  17652. set: function (collisionEnabled) {
  17653. this._checkCollisions = collisionEnabled;
  17654. if (this.getScene().workerCollisions) {
  17655. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17656. }
  17657. },
  17658. enumerable: true,
  17659. configurable: true
  17660. });
  17661. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17662. /**
  17663. * Gets Collider object used to compute collisions (not physics)
  17664. */
  17665. get: function () {
  17666. return this._collider;
  17667. },
  17668. enumerable: true,
  17669. configurable: true
  17670. });
  17671. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17672. var globalPosition = this.getAbsolutePosition();
  17673. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17674. if (!this._collider) {
  17675. this._collider = new BABYLON.Collider();
  17676. }
  17677. this._collider._radius = this.ellipsoid;
  17678. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17679. return this;
  17680. };
  17681. // Submeshes octree
  17682. /**
  17683. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17684. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17685. * Returns an Octree of submeshes.
  17686. */
  17687. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17688. if (maxCapacity === void 0) { maxCapacity = 64; }
  17689. if (maxDepth === void 0) { maxDepth = 2; }
  17690. if (!this._submeshesOctree) {
  17691. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17692. }
  17693. this.computeWorldMatrix(true);
  17694. var boundingInfo = this.getBoundingInfo();
  17695. // Update octree
  17696. var bbox = boundingInfo.boundingBox;
  17697. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17698. return this._submeshesOctree;
  17699. };
  17700. // Collisions
  17701. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17702. this._generatePointsArray();
  17703. if (!this._positions) {
  17704. return this;
  17705. }
  17706. // Transformation
  17707. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17708. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17709. subMesh._lastColliderWorldVertices = [];
  17710. subMesh._trianglePlanes = [];
  17711. var start = subMesh.verticesStart;
  17712. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17713. for (var i = start; i < end; i++) {
  17714. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17715. }
  17716. }
  17717. // Collide
  17718. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17719. if (collider.collisionFound) {
  17720. collider.collidedMesh = this;
  17721. }
  17722. return this;
  17723. };
  17724. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17725. var subMeshes;
  17726. var len;
  17727. // Octrees
  17728. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17729. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17730. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17731. len = intersections.length;
  17732. subMeshes = intersections.data;
  17733. }
  17734. else {
  17735. subMeshes = this.subMeshes;
  17736. len = subMeshes.length;
  17737. }
  17738. for (var index = 0; index < len; index++) {
  17739. var subMesh = subMeshes[index];
  17740. // Bounding test
  17741. if (len > 1 && !subMesh._checkCollision(collider))
  17742. continue;
  17743. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17744. }
  17745. return this;
  17746. };
  17747. AbstractMesh.prototype._checkCollision = function (collider) {
  17748. // Bounding box test
  17749. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17750. return this;
  17751. // Transformation matrix
  17752. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17753. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17754. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17755. return this;
  17756. };
  17757. // Picking
  17758. AbstractMesh.prototype._generatePointsArray = function () {
  17759. return false;
  17760. };
  17761. /**
  17762. * Checks if the passed Ray intersects with the mesh.
  17763. * Returns an object PickingInfo.
  17764. */
  17765. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17766. var pickingInfo = new BABYLON.PickingInfo();
  17767. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17768. return pickingInfo;
  17769. }
  17770. if (!this._generatePointsArray()) {
  17771. return pickingInfo;
  17772. }
  17773. var intersectInfo = null;
  17774. // Octrees
  17775. var subMeshes;
  17776. var len;
  17777. if (this._submeshesOctree && this.useOctreeForPicking) {
  17778. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17779. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17780. len = intersections.length;
  17781. subMeshes = intersections.data;
  17782. }
  17783. else {
  17784. subMeshes = this.subMeshes;
  17785. len = subMeshes.length;
  17786. }
  17787. for (var index = 0; index < len; index++) {
  17788. var subMesh = subMeshes[index];
  17789. // Bounding test
  17790. if (len > 1 && !subMesh.canIntersects(ray))
  17791. continue;
  17792. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17793. if (currentIntersectInfo) {
  17794. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17795. intersectInfo = currentIntersectInfo;
  17796. intersectInfo.subMeshId = index;
  17797. if (fastCheck) {
  17798. break;
  17799. }
  17800. }
  17801. }
  17802. }
  17803. if (intersectInfo) {
  17804. // Get picked point
  17805. var world = this.getWorldMatrix();
  17806. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17807. var direction = ray.direction.clone();
  17808. direction = direction.scale(intersectInfo.distance);
  17809. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17810. var pickedPoint = worldOrigin.add(worldDirection);
  17811. // Return result
  17812. pickingInfo.hit = true;
  17813. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17814. pickingInfo.pickedPoint = pickedPoint;
  17815. pickingInfo.pickedMesh = this;
  17816. pickingInfo.bu = intersectInfo.bu || 0;
  17817. pickingInfo.bv = intersectInfo.bv || 0;
  17818. pickingInfo.faceId = intersectInfo.faceId;
  17819. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17820. return pickingInfo;
  17821. }
  17822. return pickingInfo;
  17823. };
  17824. /**
  17825. * Clones the mesh, used by the class Mesh.
  17826. * Just returns `null` for an AbstractMesh.
  17827. */
  17828. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17829. return null;
  17830. };
  17831. /**
  17832. * Disposes all the mesh submeshes.
  17833. * Returns the AbstractMesh.
  17834. */
  17835. AbstractMesh.prototype.releaseSubMeshes = function () {
  17836. if (this.subMeshes) {
  17837. while (this.subMeshes.length) {
  17838. this.subMeshes[0].dispose();
  17839. }
  17840. }
  17841. else {
  17842. this.subMeshes = new Array();
  17843. }
  17844. return this;
  17845. };
  17846. /**
  17847. * Disposes the AbstractMesh.
  17848. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17849. * Returns nothing.
  17850. */
  17851. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17852. var _this = this;
  17853. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17854. var index;
  17855. // Action manager
  17856. if (this.actionManager !== undefined && this.actionManager !== null) {
  17857. this.actionManager.dispose();
  17858. this.actionManager = null;
  17859. }
  17860. // Skeleton
  17861. this.skeleton = null;
  17862. // Physics
  17863. if (this.physicsImpostor) {
  17864. this.physicsImpostor.dispose();
  17865. }
  17866. // Intersections in progress
  17867. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17868. var other = this._intersectionsInProgress[index];
  17869. var pos = other._intersectionsInProgress.indexOf(this);
  17870. other._intersectionsInProgress.splice(pos, 1);
  17871. }
  17872. this._intersectionsInProgress = [];
  17873. // Lights
  17874. var lights = this.getScene().lights;
  17875. lights.forEach(function (light) {
  17876. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17877. if (meshIndex !== -1) {
  17878. light.includedOnlyMeshes.splice(meshIndex, 1);
  17879. }
  17880. meshIndex = light.excludedMeshes.indexOf(_this);
  17881. if (meshIndex !== -1) {
  17882. light.excludedMeshes.splice(meshIndex, 1);
  17883. }
  17884. // Shadow generators
  17885. var generator = light.getShadowGenerator();
  17886. if (generator) {
  17887. var shadowMap = generator.getShadowMap();
  17888. if (shadowMap && shadowMap.renderList) {
  17889. meshIndex = shadowMap.renderList.indexOf(_this);
  17890. if (meshIndex !== -1) {
  17891. shadowMap.renderList.splice(meshIndex, 1);
  17892. }
  17893. }
  17894. }
  17895. });
  17896. // Edges
  17897. if (this._edgesRenderer) {
  17898. this._edgesRenderer.dispose();
  17899. this._edgesRenderer = null;
  17900. }
  17901. // SubMeshes
  17902. if (this.getClassName() !== "InstancedMesh") {
  17903. this.releaseSubMeshes();
  17904. }
  17905. // Octree
  17906. var sceneOctree = this.getScene().selectionOctree;
  17907. if (sceneOctree !== undefined && sceneOctree !== null) {
  17908. var index = sceneOctree.dynamicContent.indexOf(this);
  17909. if (index !== -1) {
  17910. sceneOctree.dynamicContent.splice(index, 1);
  17911. }
  17912. }
  17913. // Query
  17914. var engine = this.getScene().getEngine();
  17915. if (this._occlusionQuery) {
  17916. this._isOcclusionQueryInProgress = false;
  17917. engine.deleteQuery(this._occlusionQuery);
  17918. this._occlusionQuery = null;
  17919. }
  17920. // Engine
  17921. engine.wipeCaches();
  17922. // Remove from scene
  17923. this.getScene().removeMesh(this);
  17924. if (disposeMaterialAndTextures) {
  17925. if (this.material) {
  17926. this.material.dispose(false, true);
  17927. }
  17928. }
  17929. if (!doNotRecurse) {
  17930. // Particles
  17931. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  17932. if (this.getScene().particleSystems[index].emitter === this) {
  17933. this.getScene().particleSystems[index].dispose();
  17934. index--;
  17935. }
  17936. }
  17937. }
  17938. // facet data
  17939. if (this._facetDataEnabled) {
  17940. this.disableFacetData();
  17941. }
  17942. this.onAfterWorldMatrixUpdateObservable.clear();
  17943. this.onCollideObservable.clear();
  17944. this.onCollisionPositionChangeObservable.clear();
  17945. this._isDisposed = true;
  17946. _super.prototype.dispose.call(this, doNotRecurse);
  17947. };
  17948. /**
  17949. * Adds the passed mesh as a child to the current mesh.
  17950. * Returns the AbstractMesh.
  17951. */
  17952. AbstractMesh.prototype.addChild = function (mesh) {
  17953. mesh.setParent(this);
  17954. return this;
  17955. };
  17956. /**
  17957. * Removes the passed mesh from the current mesh children list.
  17958. * Returns the AbstractMesh.
  17959. */
  17960. AbstractMesh.prototype.removeChild = function (mesh) {
  17961. mesh.setParent(null);
  17962. return this;
  17963. };
  17964. // Facet data
  17965. /**
  17966. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  17967. * Returns the AbstractMesh.
  17968. */
  17969. AbstractMesh.prototype._initFacetData = function () {
  17970. if (!this._facetNormals) {
  17971. this._facetNormals = new Array();
  17972. }
  17973. if (!this._facetPositions) {
  17974. this._facetPositions = new Array();
  17975. }
  17976. if (!this._facetPartitioning) {
  17977. this._facetPartitioning = new Array();
  17978. }
  17979. this._facetNb = (this.getIndices().length / 3) | 0;
  17980. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  17981. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  17982. for (var f = 0; f < this._facetNb; f++) {
  17983. this._facetNormals[f] = BABYLON.Vector3.Zero();
  17984. this._facetPositions[f] = BABYLON.Vector3.Zero();
  17985. }
  17986. this._facetDataEnabled = true;
  17987. return this;
  17988. };
  17989. /**
  17990. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  17991. * This method can be called within the render loop.
  17992. * 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.
  17993. * Returns the AbstractMesh.
  17994. */
  17995. AbstractMesh.prototype.updateFacetData = function () {
  17996. if (!this._facetDataEnabled) {
  17997. this._initFacetData();
  17998. }
  17999. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18000. var indices = this.getIndices();
  18001. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18002. var bInfo = this.getBoundingInfo();
  18003. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18004. // init arrays, matrix and sort function on first call
  18005. this._facetDepthSortEnabled = true;
  18006. if (indices instanceof Uint16Array) {
  18007. this._depthSortedIndices = new Uint16Array(indices);
  18008. }
  18009. else if (indices instanceof Uint32Array) {
  18010. this._depthSortedIndices = new Uint32Array(indices);
  18011. }
  18012. else {
  18013. var needs32bits = false;
  18014. for (var i = 0; i < indices.length; i++) {
  18015. if (indices[i] > 65535) {
  18016. needs32bits = true;
  18017. break;
  18018. }
  18019. }
  18020. if (needs32bits) {
  18021. this._depthSortedIndices = new Uint32Array(indices);
  18022. }
  18023. else {
  18024. this._depthSortedIndices = new Uint16Array(indices);
  18025. }
  18026. }
  18027. this._facetDepthSortFunction = function (f1, f2) {
  18028. return (f2.sqDistance - f1.sqDistance);
  18029. };
  18030. if (!this._facetDepthSortFrom) {
  18031. var camera = this.getScene().activeCamera;
  18032. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18033. }
  18034. this._depthSortedFacets = [];
  18035. for (var f = 0; f < this._facetNb; f++) {
  18036. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18037. this._depthSortedFacets.push(depthSortedFacet);
  18038. }
  18039. this._invertedMatrix = BABYLON.Matrix.Identity();
  18040. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18041. }
  18042. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18043. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18044. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18045. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18046. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18047. this._subDiv.max = this._partitioningSubdivisions;
  18048. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18049. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18050. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18051. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18052. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18053. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18054. // set the parameters for ComputeNormals()
  18055. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18056. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18057. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18058. this._facetParameters.bInfo = bInfo;
  18059. this._facetParameters.bbSize = this._bbSize;
  18060. this._facetParameters.subDiv = this._subDiv;
  18061. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18062. this._facetParameters.depthSort = this._facetDepthSort;
  18063. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18064. this.computeWorldMatrix(true);
  18065. this._worldMatrix.invertToRef(this._invertedMatrix);
  18066. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18067. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18068. }
  18069. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18070. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18071. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18072. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18073. var l = (this._depthSortedIndices.length / 3) | 0;
  18074. for (var f = 0; f < l; f++) {
  18075. var sind = this._depthSortedFacets[f].ind;
  18076. this._depthSortedIndices[f * 3] = indices[sind];
  18077. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18078. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18079. }
  18080. this.updateIndices(this._depthSortedIndices);
  18081. }
  18082. return this;
  18083. };
  18084. /**
  18085. * Returns the facetLocalNormals array.
  18086. * The normals are expressed in the mesh local space.
  18087. */
  18088. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18089. if (!this._facetNormals) {
  18090. this.updateFacetData();
  18091. }
  18092. return this._facetNormals;
  18093. };
  18094. /**
  18095. * Returns the facetLocalPositions array.
  18096. * The facet positions are expressed in the mesh local space.
  18097. */
  18098. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18099. if (!this._facetPositions) {
  18100. this.updateFacetData();
  18101. }
  18102. return this._facetPositions;
  18103. };
  18104. /**
  18105. * Returns the facetLocalPartioning array.
  18106. */
  18107. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18108. if (!this._facetPartitioning) {
  18109. this.updateFacetData();
  18110. }
  18111. return this._facetPartitioning;
  18112. };
  18113. /**
  18114. * Returns the i-th facet position in the world system.
  18115. * This method allocates a new Vector3 per call.
  18116. */
  18117. AbstractMesh.prototype.getFacetPosition = function (i) {
  18118. var pos = BABYLON.Vector3.Zero();
  18119. this.getFacetPositionToRef(i, pos);
  18120. return pos;
  18121. };
  18122. /**
  18123. * Sets the reference Vector3 with the i-th facet position in the world system.
  18124. * Returns the AbstractMesh.
  18125. */
  18126. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18127. var localPos = (this.getFacetLocalPositions())[i];
  18128. var world = this.getWorldMatrix();
  18129. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18130. return this;
  18131. };
  18132. /**
  18133. * Returns the i-th facet normal in the world system.
  18134. * This method allocates a new Vector3 per call.
  18135. */
  18136. AbstractMesh.prototype.getFacetNormal = function (i) {
  18137. var norm = BABYLON.Vector3.Zero();
  18138. this.getFacetNormalToRef(i, norm);
  18139. return norm;
  18140. };
  18141. /**
  18142. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18143. * Returns the AbstractMesh.
  18144. */
  18145. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18146. var localNorm = (this.getFacetLocalNormals())[i];
  18147. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18148. return this;
  18149. };
  18150. /**
  18151. * 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).
  18152. */
  18153. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18154. var bInfo = this.getBoundingInfo();
  18155. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18156. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18157. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18158. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18159. return null;
  18160. }
  18161. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18162. };
  18163. /**
  18164. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18165. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18166. * If checkFace is 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.
  18167. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18168. * 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.
  18169. */
  18170. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18171. if (checkFace === void 0) { checkFace = false; }
  18172. if (facing === void 0) { facing = true; }
  18173. var world = this.getWorldMatrix();
  18174. var invMat = BABYLON.Tmp.Matrix[5];
  18175. world.invertToRef(invMat);
  18176. var invVect = BABYLON.Tmp.Vector3[8];
  18177. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18178. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18179. if (projected) {
  18180. // tranform the local computed projected vector to world coordinates
  18181. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18182. }
  18183. return closest;
  18184. };
  18185. /**
  18186. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18187. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18188. * If checkFace is 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.
  18189. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18190. * 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.
  18191. */
  18192. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18193. if (checkFace === void 0) { checkFace = false; }
  18194. if (facing === void 0) { facing = true; }
  18195. var closest = null;
  18196. var tmpx = 0.0;
  18197. var tmpy = 0.0;
  18198. var tmpz = 0.0;
  18199. var d = 0.0; // tmp dot facet normal * facet position
  18200. var t0 = 0.0;
  18201. var projx = 0.0;
  18202. var projy = 0.0;
  18203. var projz = 0.0;
  18204. // Get all the facets in the same partitioning block than (x, y, z)
  18205. var facetPositions = this.getFacetLocalPositions();
  18206. var facetNormals = this.getFacetLocalNormals();
  18207. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18208. if (!facetsInBlock) {
  18209. return null;
  18210. }
  18211. // Get the closest facet to (x, y, z)
  18212. var shortest = Number.MAX_VALUE; // init distance vars
  18213. var tmpDistance = shortest;
  18214. var fib; // current facet in the block
  18215. var norm; // current facet normal
  18216. var p0; // current facet barycenter position
  18217. // loop on all the facets in the current partitioning block
  18218. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18219. fib = facetsInBlock[idx];
  18220. norm = facetNormals[fib];
  18221. p0 = facetPositions[fib];
  18222. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18223. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18224. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18225. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18226. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18227. projx = x + norm.x * t0;
  18228. projy = y + norm.y * t0;
  18229. projz = z + norm.z * t0;
  18230. tmpx = projx - x;
  18231. tmpy = projy - y;
  18232. tmpz = projz - z;
  18233. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18234. if (tmpDistance < shortest) {
  18235. shortest = tmpDistance;
  18236. closest = fib;
  18237. if (projected) {
  18238. projected.x = projx;
  18239. projected.y = projy;
  18240. projected.z = projz;
  18241. }
  18242. }
  18243. }
  18244. }
  18245. return closest;
  18246. };
  18247. /**
  18248. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18249. */
  18250. AbstractMesh.prototype.getFacetDataParameters = function () {
  18251. return this._facetParameters;
  18252. };
  18253. /**
  18254. * Disables the feature FacetData and frees the related memory.
  18255. * Returns the AbstractMesh.
  18256. */
  18257. AbstractMesh.prototype.disableFacetData = function () {
  18258. if (this._facetDataEnabled) {
  18259. this._facetDataEnabled = false;
  18260. this._facetPositions = new Array();
  18261. this._facetNormals = new Array();
  18262. this._facetPartitioning = new Array();
  18263. this._facetParameters = null;
  18264. this._depthSortedIndices = new Uint32Array(0);
  18265. }
  18266. return this;
  18267. };
  18268. /**
  18269. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18270. * Returns the mesh.
  18271. */
  18272. AbstractMesh.prototype.updateIndices = function (indices) {
  18273. return this;
  18274. };
  18275. /**
  18276. * The mesh Geometry. Actually used by the Mesh object.
  18277. * Returns a blank geometry object.
  18278. */
  18279. /**
  18280. * Creates new normals data for the mesh.
  18281. * @param updatable.
  18282. */
  18283. AbstractMesh.prototype.createNormals = function (updatable) {
  18284. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18285. var indices = this.getIndices();
  18286. var normals;
  18287. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18288. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18289. }
  18290. else {
  18291. normals = [];
  18292. }
  18293. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18294. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18295. };
  18296. /**
  18297. * Align the mesh with a normal.
  18298. * Returns the mesh.
  18299. */
  18300. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18301. if (!upDirection) {
  18302. upDirection = BABYLON.Axis.Y;
  18303. }
  18304. var axisX = BABYLON.Tmp.Vector3[0];
  18305. var axisZ = BABYLON.Tmp.Vector3[1];
  18306. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18307. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18308. if (this.rotationQuaternion) {
  18309. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18310. }
  18311. else {
  18312. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18313. }
  18314. return this;
  18315. };
  18316. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18317. var engine = this.getEngine();
  18318. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18319. this._isOccluded = false;
  18320. return;
  18321. }
  18322. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18323. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18324. if (isOcclusionQueryAvailable) {
  18325. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18326. this._isOcclusionQueryInProgress = false;
  18327. this._occlusionInternalRetryCounter = 0;
  18328. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18329. }
  18330. else {
  18331. this._occlusionInternalRetryCounter++;
  18332. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18333. this._isOcclusionQueryInProgress = false;
  18334. this._occlusionInternalRetryCounter = 0;
  18335. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18336. // if strict continue the last state of the object.
  18337. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18338. }
  18339. else {
  18340. return;
  18341. }
  18342. }
  18343. }
  18344. var scene = this.getScene();
  18345. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18346. if (!this._occlusionQuery) {
  18347. this._occlusionQuery = engine.createQuery();
  18348. }
  18349. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18350. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18351. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18352. this._isOcclusionQueryInProgress = true;
  18353. };
  18354. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18355. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18356. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18357. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18358. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18359. return AbstractMesh;
  18360. }(BABYLON.TransformNode));
  18361. BABYLON.AbstractMesh = AbstractMesh;
  18362. })(BABYLON || (BABYLON = {}));
  18363. //# sourceMappingURL=babylon.abstractMesh.js.map
  18364. var BABYLON;
  18365. (function (BABYLON) {
  18366. /**
  18367. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18368. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18369. * 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.
  18370. */
  18371. var Light = /** @class */ (function (_super) {
  18372. __extends(Light, _super);
  18373. /**
  18374. * Creates a Light object in the scene.
  18375. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18376. * @param name The firendly name of the light
  18377. * @param scene The scene the light belongs too
  18378. */
  18379. function Light(name, scene) {
  18380. var _this = _super.call(this, name, scene) || this;
  18381. /**
  18382. * Diffuse gives the basic color to an object.
  18383. */
  18384. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18385. /**
  18386. * Specular produces a highlight color on an object.
  18387. * Note: This is note affecting PBR materials.
  18388. */
  18389. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18390. /**
  18391. * Strength of the light.
  18392. * Note: By default it is define in the framework own unit.
  18393. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18394. */
  18395. _this.intensity = 1.0;
  18396. /**
  18397. * Defines how far from the source the light is impacting in scene units.
  18398. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18399. */
  18400. _this.range = Number.MAX_VALUE;
  18401. /**
  18402. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18403. * of light.
  18404. */
  18405. _this._photometricScale = 1.0;
  18406. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18407. _this._radius = 0.00001;
  18408. /**
  18409. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18410. * exceeding the number allowed of the materials.
  18411. */
  18412. _this.renderPriority = 0;
  18413. /**
  18414. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18415. * the current shadow generator.
  18416. */
  18417. _this.shadowEnabled = true;
  18418. _this._excludeWithLayerMask = 0;
  18419. _this._includeOnlyWithLayerMask = 0;
  18420. _this._lightmapMode = 0;
  18421. /**
  18422. * @ignore Internal use only.
  18423. */
  18424. _this._excludedMeshesIds = new Array();
  18425. /**
  18426. * @ignore Internal use only.
  18427. */
  18428. _this._includedOnlyMeshesIds = new Array();
  18429. _this.getScene().addLight(_this);
  18430. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18431. _this._buildUniformLayout();
  18432. _this.includedOnlyMeshes = new Array();
  18433. _this.excludedMeshes = new Array();
  18434. _this._resyncMeshes();
  18435. return _this;
  18436. }
  18437. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18438. /**
  18439. * If every light affecting the material is in this lightmapMode,
  18440. * material.lightmapTexture adds or multiplies
  18441. * (depends on material.useLightmapAsShadowmap)
  18442. * after every other light calculations.
  18443. */
  18444. get: function () {
  18445. return Light._LIGHTMAP_DEFAULT;
  18446. },
  18447. enumerable: true,
  18448. configurable: true
  18449. });
  18450. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18451. /**
  18452. * material.lightmapTexture as only diffuse lighting from this light
  18453. * adds only specular lighting from this light
  18454. * adds dynamic shadows
  18455. */
  18456. get: function () {
  18457. return Light._LIGHTMAP_SPECULAR;
  18458. },
  18459. enumerable: true,
  18460. configurable: true
  18461. });
  18462. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18463. /**
  18464. * material.lightmapTexture as only lighting
  18465. * no light calculation from this light
  18466. * only adds dynamic shadows from this light
  18467. */
  18468. get: function () {
  18469. return Light._LIGHTMAP_SHADOWSONLY;
  18470. },
  18471. enumerable: true,
  18472. configurable: true
  18473. });
  18474. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18475. /**
  18476. * Each light type uses the default quantity according to its type:
  18477. * point/spot lights use luminous intensity
  18478. * directional lights use illuminance
  18479. */
  18480. get: function () {
  18481. return Light._INTENSITYMODE_AUTOMATIC;
  18482. },
  18483. enumerable: true,
  18484. configurable: true
  18485. });
  18486. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18487. /**
  18488. * lumen (lm)
  18489. */
  18490. get: function () {
  18491. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18492. },
  18493. enumerable: true,
  18494. configurable: true
  18495. });
  18496. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18497. /**
  18498. * candela (lm/sr)
  18499. */
  18500. get: function () {
  18501. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18502. },
  18503. enumerable: true,
  18504. configurable: true
  18505. });
  18506. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18507. /**
  18508. * lux (lm/m^2)
  18509. */
  18510. get: function () {
  18511. return Light._INTENSITYMODE_ILLUMINANCE;
  18512. },
  18513. enumerable: true,
  18514. configurable: true
  18515. });
  18516. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18517. /**
  18518. * nit (cd/m^2)
  18519. */
  18520. get: function () {
  18521. return Light._INTENSITYMODE_LUMINANCE;
  18522. },
  18523. enumerable: true,
  18524. configurable: true
  18525. });
  18526. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18527. /**
  18528. * Light type const id of the point light.
  18529. */
  18530. get: function () {
  18531. return Light._LIGHTTYPEID_POINTLIGHT;
  18532. },
  18533. enumerable: true,
  18534. configurable: true
  18535. });
  18536. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18537. /**
  18538. * Light type const id of the directional light.
  18539. */
  18540. get: function () {
  18541. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18542. },
  18543. enumerable: true,
  18544. configurable: true
  18545. });
  18546. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18547. /**
  18548. * Light type const id of the spot light.
  18549. */
  18550. get: function () {
  18551. return Light._LIGHTTYPEID_SPOTLIGHT;
  18552. },
  18553. enumerable: true,
  18554. configurable: true
  18555. });
  18556. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18557. /**
  18558. * Light type const id of the hemispheric light.
  18559. */
  18560. get: function () {
  18561. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18562. },
  18563. enumerable: true,
  18564. configurable: true
  18565. });
  18566. Object.defineProperty(Light.prototype, "intensityMode", {
  18567. /**
  18568. * Gets the photometric scale used to interpret the intensity.
  18569. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18570. */
  18571. get: function () {
  18572. return this._intensityMode;
  18573. },
  18574. /**
  18575. * Sets the photometric scale used to interpret the intensity.
  18576. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18577. */
  18578. set: function (value) {
  18579. this._intensityMode = value;
  18580. this._computePhotometricScale();
  18581. },
  18582. enumerable: true,
  18583. configurable: true
  18584. });
  18585. ;
  18586. ;
  18587. Object.defineProperty(Light.prototype, "radius", {
  18588. /**
  18589. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18590. */
  18591. get: function () {
  18592. return this._radius;
  18593. },
  18594. /**
  18595. * sets the light radius used by PBR Materials to simulate soft area lights.
  18596. */
  18597. set: function (value) {
  18598. this._radius = value;
  18599. this._computePhotometricScale();
  18600. },
  18601. enumerable: true,
  18602. configurable: true
  18603. });
  18604. ;
  18605. ;
  18606. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18607. /**
  18608. * Gets the only meshes impacted by this light.
  18609. */
  18610. get: function () {
  18611. return this._includedOnlyMeshes;
  18612. },
  18613. /**
  18614. * Sets the only meshes impacted by this light.
  18615. */
  18616. set: function (value) {
  18617. this._includedOnlyMeshes = value;
  18618. this._hookArrayForIncludedOnly(value);
  18619. },
  18620. enumerable: true,
  18621. configurable: true
  18622. });
  18623. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18624. /**
  18625. * Gets the meshes not impacted by this light.
  18626. */
  18627. get: function () {
  18628. return this._excludedMeshes;
  18629. },
  18630. /**
  18631. * Sets the meshes not impacted by this light.
  18632. */
  18633. set: function (value) {
  18634. this._excludedMeshes = value;
  18635. this._hookArrayForExcluded(value);
  18636. },
  18637. enumerable: true,
  18638. configurable: true
  18639. });
  18640. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18641. /**
  18642. * Gets the layer id use to find what meshes are not impacted by the light.
  18643. * Inactive if 0
  18644. */
  18645. get: function () {
  18646. return this._excludeWithLayerMask;
  18647. },
  18648. /**
  18649. * Sets the layer id use to find what meshes are not impacted by the light.
  18650. * Inactive if 0
  18651. */
  18652. set: function (value) {
  18653. this._excludeWithLayerMask = value;
  18654. this._resyncMeshes();
  18655. },
  18656. enumerable: true,
  18657. configurable: true
  18658. });
  18659. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18660. /**
  18661. * Gets the layer id use to find what meshes are impacted by the light.
  18662. * Inactive if 0
  18663. */
  18664. get: function () {
  18665. return this._includeOnlyWithLayerMask;
  18666. },
  18667. /**
  18668. * Sets the layer id use to find what meshes are impacted by the light.
  18669. * Inactive if 0
  18670. */
  18671. set: function (value) {
  18672. this._includeOnlyWithLayerMask = value;
  18673. this._resyncMeshes();
  18674. },
  18675. enumerable: true,
  18676. configurable: true
  18677. });
  18678. Object.defineProperty(Light.prototype, "lightmapMode", {
  18679. /**
  18680. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18681. */
  18682. get: function () {
  18683. return this._lightmapMode;
  18684. },
  18685. /**
  18686. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18687. */
  18688. set: function (value) {
  18689. if (this._lightmapMode === value) {
  18690. return;
  18691. }
  18692. this._lightmapMode = value;
  18693. this._markMeshesAsLightDirty();
  18694. },
  18695. enumerable: true,
  18696. configurable: true
  18697. });
  18698. /**
  18699. * Returns the string "Light".
  18700. * @returns the class name
  18701. */
  18702. Light.prototype.getClassName = function () {
  18703. return "Light";
  18704. };
  18705. /**
  18706. * Converts the light information to a readable string for debug purpose.
  18707. * @param fullDetails Supports for multiple levels of logging within scene loading
  18708. * @returns the human readable light info
  18709. */
  18710. Light.prototype.toString = function (fullDetails) {
  18711. var ret = "Name: " + this.name;
  18712. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18713. if (this.animations) {
  18714. for (var i = 0; i < this.animations.length; i++) {
  18715. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18716. }
  18717. }
  18718. if (fullDetails) {
  18719. }
  18720. return ret;
  18721. };
  18722. /**
  18723. * Set the enabled state of this node.
  18724. * @param value - the new enabled state
  18725. * @see isEnabled
  18726. */
  18727. Light.prototype.setEnabled = function (value) {
  18728. _super.prototype.setEnabled.call(this, value);
  18729. this._resyncMeshes();
  18730. };
  18731. /**
  18732. * Returns the Light associated shadow generator if any.
  18733. * @return the associated shadow generator.
  18734. */
  18735. Light.prototype.getShadowGenerator = function () {
  18736. return this._shadowGenerator;
  18737. };
  18738. /**
  18739. * Returns a Vector3, the absolute light position in the World.
  18740. * @returns the world space position of the light
  18741. */
  18742. Light.prototype.getAbsolutePosition = function () {
  18743. return BABYLON.Vector3.Zero();
  18744. };
  18745. /**
  18746. * Specifies if the light will affect the passed mesh.
  18747. * @param mesh The mesh to test against the light
  18748. * @return true the mesh is affected otherwise, false.
  18749. */
  18750. Light.prototype.canAffectMesh = function (mesh) {
  18751. if (!mesh) {
  18752. return true;
  18753. }
  18754. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18755. return false;
  18756. }
  18757. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18758. return false;
  18759. }
  18760. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18761. return false;
  18762. }
  18763. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18764. return false;
  18765. }
  18766. return true;
  18767. };
  18768. /**
  18769. * Computes and Returns the light World matrix.
  18770. * @returns the world matrix
  18771. */
  18772. Light.prototype.getWorldMatrix = function () {
  18773. this._currentRenderId = this.getScene().getRenderId();
  18774. var worldMatrix = this._getWorldMatrix();
  18775. if (this.parent && this.parent.getWorldMatrix) {
  18776. if (!this._parentedWorldMatrix) {
  18777. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18778. }
  18779. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18780. this._markSyncedWithParent();
  18781. return this._parentedWorldMatrix;
  18782. }
  18783. return worldMatrix;
  18784. };
  18785. /**
  18786. * Sort function to order lights for rendering.
  18787. * @param a First Light object to compare to second.
  18788. * @param b Second Light object to compare first.
  18789. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18790. */
  18791. Light.CompareLightsPriority = function (a, b) {
  18792. //shadow-casting lights have priority over non-shadow-casting lights
  18793. //the renderPrioirty is a secondary sort criterion
  18794. if (a.shadowEnabled !== b.shadowEnabled) {
  18795. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18796. }
  18797. return b.renderPriority - a.renderPriority;
  18798. };
  18799. /**
  18800. * Disposes the light.
  18801. */
  18802. Light.prototype.dispose = function () {
  18803. if (this._shadowGenerator) {
  18804. this._shadowGenerator.dispose();
  18805. this._shadowGenerator = null;
  18806. }
  18807. // Animations
  18808. this.getScene().stopAnimation(this);
  18809. // Remove from meshes
  18810. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18811. var mesh = _a[_i];
  18812. mesh._removeLightSource(this);
  18813. }
  18814. this._uniformBuffer.dispose();
  18815. // Remove from scene
  18816. this.getScene().removeLight(this);
  18817. _super.prototype.dispose.call(this);
  18818. };
  18819. /**
  18820. * Returns the light type ID (integer).
  18821. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18822. */
  18823. Light.prototype.getTypeID = function () {
  18824. return 0;
  18825. };
  18826. /**
  18827. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18828. * @returns the scaled intensity in intensity mode unit
  18829. */
  18830. Light.prototype.getScaledIntensity = function () {
  18831. return this._photometricScale * this.intensity;
  18832. };
  18833. /**
  18834. * Returns a new Light object, named "name", from the current one.
  18835. * @param name The name of the cloned light
  18836. * @returns the new created light
  18837. */
  18838. Light.prototype.clone = function (name) {
  18839. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18840. if (!constructor) {
  18841. return null;
  18842. }
  18843. return BABYLON.SerializationHelper.Clone(constructor, this);
  18844. };
  18845. /**
  18846. * Serializes the current light into a Serialization object.
  18847. * @returns the serialized object.
  18848. */
  18849. Light.prototype.serialize = function () {
  18850. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18851. // Type
  18852. serializationObject.type = this.getTypeID();
  18853. // Parent
  18854. if (this.parent) {
  18855. serializationObject.parentId = this.parent.id;
  18856. }
  18857. // Inclusion / exclusions
  18858. if (this.excludedMeshes.length > 0) {
  18859. serializationObject.excludedMeshesIds = [];
  18860. this.excludedMeshes.forEach(function (mesh) {
  18861. serializationObject.excludedMeshesIds.push(mesh.id);
  18862. });
  18863. }
  18864. if (this.includedOnlyMeshes.length > 0) {
  18865. serializationObject.includedOnlyMeshesIds = [];
  18866. this.includedOnlyMeshes.forEach(function (mesh) {
  18867. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18868. });
  18869. }
  18870. // Animations
  18871. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18872. serializationObject.ranges = this.serializeAnimationRanges();
  18873. return serializationObject;
  18874. };
  18875. /**
  18876. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18877. * This new light is named "name" and added to the passed scene.
  18878. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18879. * @param name The friendly name of the light
  18880. * @param scene The scene the new light will belong to
  18881. * @returns the constructor function
  18882. */
  18883. Light.GetConstructorFromName = function (type, name, scene) {
  18884. switch (type) {
  18885. case 0:
  18886. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18887. case 1:
  18888. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18889. case 2:
  18890. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18891. case 3:
  18892. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18893. }
  18894. return null;
  18895. };
  18896. /**
  18897. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  18898. * @param parsedLight The JSON representation of the light
  18899. * @param scene The scene to create the parsed light in
  18900. * @returns the created light after parsing
  18901. */
  18902. Light.Parse = function (parsedLight, scene) {
  18903. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  18904. if (!constructor) {
  18905. return null;
  18906. }
  18907. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  18908. // Inclusion / exclusions
  18909. if (parsedLight.excludedMeshesIds) {
  18910. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18911. }
  18912. if (parsedLight.includedOnlyMeshesIds) {
  18913. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18914. }
  18915. // Parent
  18916. if (parsedLight.parentId) {
  18917. light._waitingParentId = parsedLight.parentId;
  18918. }
  18919. // Animations
  18920. if (parsedLight.animations) {
  18921. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18922. var parsedAnimation = parsedLight.animations[animationIndex];
  18923. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18924. }
  18925. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  18926. }
  18927. if (parsedLight.autoAnimate) {
  18928. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  18929. }
  18930. return light;
  18931. };
  18932. Light.prototype._hookArrayForExcluded = function (array) {
  18933. var _this = this;
  18934. var oldPush = array.push;
  18935. array.push = function () {
  18936. var items = [];
  18937. for (var _i = 0; _i < arguments.length; _i++) {
  18938. items[_i] = arguments[_i];
  18939. }
  18940. var result = oldPush.apply(array, items);
  18941. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  18942. var item = items_1[_a];
  18943. item._resyncLighSource(_this);
  18944. }
  18945. return result;
  18946. };
  18947. var oldSplice = array.splice;
  18948. array.splice = function (index, deleteCount) {
  18949. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18950. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  18951. var item = deleted_1[_i];
  18952. item._resyncLighSource(_this);
  18953. }
  18954. return deleted;
  18955. };
  18956. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  18957. var item = array_1[_i];
  18958. item._resyncLighSource(this);
  18959. }
  18960. };
  18961. Light.prototype._hookArrayForIncludedOnly = function (array) {
  18962. var _this = this;
  18963. var oldPush = array.push;
  18964. array.push = function () {
  18965. var items = [];
  18966. for (var _i = 0; _i < arguments.length; _i++) {
  18967. items[_i] = arguments[_i];
  18968. }
  18969. var result = oldPush.apply(array, items);
  18970. _this._resyncMeshes();
  18971. return result;
  18972. };
  18973. var oldSplice = array.splice;
  18974. array.splice = function (index, deleteCount) {
  18975. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18976. _this._resyncMeshes();
  18977. return deleted;
  18978. };
  18979. this._resyncMeshes();
  18980. };
  18981. Light.prototype._resyncMeshes = function () {
  18982. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18983. var mesh = _a[_i];
  18984. mesh._resyncLighSource(this);
  18985. }
  18986. };
  18987. /**
  18988. * Forces the meshes to update their light related information in their rendering used effects
  18989. * @ignore Internal Use Only
  18990. */
  18991. Light.prototype._markMeshesAsLightDirty = function () {
  18992. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18993. var mesh = _a[_i];
  18994. if (mesh._lightSources.indexOf(this) !== -1) {
  18995. mesh._markSubMeshesAsLightDirty();
  18996. }
  18997. }
  18998. };
  18999. /**
  19000. * Recomputes the cached photometric scale if needed.
  19001. */
  19002. Light.prototype._computePhotometricScale = function () {
  19003. this._photometricScale = this._getPhotometricScale();
  19004. this.getScene().resetCachedMaterial();
  19005. };
  19006. /**
  19007. * Returns the Photometric Scale according to the light type and intensity mode.
  19008. */
  19009. Light.prototype._getPhotometricScale = function () {
  19010. var photometricScale = 0.0;
  19011. var lightTypeID = this.getTypeID();
  19012. //get photometric mode
  19013. var photometricMode = this.intensityMode;
  19014. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19015. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19016. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19017. }
  19018. else {
  19019. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19020. }
  19021. }
  19022. //compute photometric scale
  19023. switch (lightTypeID) {
  19024. case Light.LIGHTTYPEID_POINTLIGHT:
  19025. case Light.LIGHTTYPEID_SPOTLIGHT:
  19026. switch (photometricMode) {
  19027. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19028. photometricScale = 1.0 / (4.0 * Math.PI);
  19029. break;
  19030. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19031. photometricScale = 1.0;
  19032. break;
  19033. case Light.INTENSITYMODE_LUMINANCE:
  19034. photometricScale = this.radius * this.radius;
  19035. break;
  19036. }
  19037. break;
  19038. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19039. switch (photometricMode) {
  19040. case Light.INTENSITYMODE_ILLUMINANCE:
  19041. photometricScale = 1.0;
  19042. break;
  19043. case Light.INTENSITYMODE_LUMINANCE:
  19044. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19045. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19046. var apexAngleRadians = this.radius;
  19047. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19048. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19049. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19050. photometricScale = solidAngle;
  19051. break;
  19052. }
  19053. break;
  19054. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19055. // No fall off in hemisperic light.
  19056. photometricScale = 1.0;
  19057. break;
  19058. }
  19059. return photometricScale;
  19060. };
  19061. /**
  19062. * Reorder the light in the scene according to their defined priority.
  19063. * @ignore Internal Use Only
  19064. */
  19065. Light.prototype._reorderLightsInScene = function () {
  19066. var scene = this.getScene();
  19067. if (this._renderPriority != 0) {
  19068. scene.requireLightSorting = true;
  19069. }
  19070. this.getScene().sortLightsByPriority();
  19071. };
  19072. //lightmapMode Consts
  19073. Light._LIGHTMAP_DEFAULT = 0;
  19074. Light._LIGHTMAP_SPECULAR = 1;
  19075. Light._LIGHTMAP_SHADOWSONLY = 2;
  19076. // Intensity Mode Consts
  19077. Light._INTENSITYMODE_AUTOMATIC = 0;
  19078. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19079. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19080. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19081. Light._INTENSITYMODE_LUMINANCE = 4;
  19082. // Light types ids const.
  19083. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19084. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19085. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19086. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19087. __decorate([
  19088. BABYLON.serializeAsColor3()
  19089. ], Light.prototype, "diffuse", void 0);
  19090. __decorate([
  19091. BABYLON.serializeAsColor3()
  19092. ], Light.prototype, "specular", void 0);
  19093. __decorate([
  19094. BABYLON.serialize()
  19095. ], Light.prototype, "intensity", void 0);
  19096. __decorate([
  19097. BABYLON.serialize()
  19098. ], Light.prototype, "range", void 0);
  19099. __decorate([
  19100. BABYLON.serialize()
  19101. ], Light.prototype, "intensityMode", null);
  19102. __decorate([
  19103. BABYLON.serialize()
  19104. ], Light.prototype, "radius", null);
  19105. __decorate([
  19106. BABYLON.serialize()
  19107. ], Light.prototype, "_renderPriority", void 0);
  19108. __decorate([
  19109. BABYLON.expandToProperty("_reorderLightsInScene")
  19110. ], Light.prototype, "renderPriority", void 0);
  19111. __decorate([
  19112. BABYLON.serialize()
  19113. ], Light.prototype, "shadowEnabled", void 0);
  19114. __decorate([
  19115. BABYLON.serialize("excludeWithLayerMask")
  19116. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19117. __decorate([
  19118. BABYLON.serialize("includeOnlyWithLayerMask")
  19119. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19120. __decorate([
  19121. BABYLON.serialize("lightmapMode")
  19122. ], Light.prototype, "_lightmapMode", void 0);
  19123. return Light;
  19124. }(BABYLON.Node));
  19125. BABYLON.Light = Light;
  19126. })(BABYLON || (BABYLON = {}));
  19127. //# sourceMappingURL=babylon.light.js.map
  19128. var BABYLON;
  19129. (function (BABYLON) {
  19130. var Camera = /** @class */ (function (_super) {
  19131. __extends(Camera, _super);
  19132. function Camera(name, position, scene) {
  19133. var _this = _super.call(this, name, scene) || this;
  19134. /**
  19135. * The vector the camera should consider as up.
  19136. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19137. */
  19138. _this.upVector = BABYLON.Vector3.Up();
  19139. _this.orthoLeft = null;
  19140. _this.orthoRight = null;
  19141. _this.orthoBottom = null;
  19142. _this.orthoTop = null;
  19143. /**
  19144. * FOV is set in Radians. (default is 0.8)
  19145. */
  19146. _this.fov = 0.8;
  19147. _this.minZ = 1;
  19148. _this.maxZ = 10000.0;
  19149. _this.inertia = 0.9;
  19150. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19151. _this.isIntermediate = false;
  19152. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19153. /**
  19154. * Restricts the camera to viewing objects with the same layerMask.
  19155. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19156. */
  19157. _this.layerMask = 0x0FFFFFFF;
  19158. /**
  19159. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19160. */
  19161. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19162. // Camera rig members
  19163. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19164. _this._rigCameras = new Array();
  19165. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19166. _this._skipRendering = false;
  19167. _this.customRenderTargets = new Array();
  19168. // Observables
  19169. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19170. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19171. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19172. _this.onRestoreStateObservable = new BABYLON.Observable();
  19173. // Cache
  19174. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19175. _this._projectionMatrix = new BABYLON.Matrix();
  19176. _this._doNotComputeProjectionMatrix = false;
  19177. _this._postProcesses = new Array();
  19178. _this._transformMatrix = BABYLON.Matrix.Zero();
  19179. _this._activeMeshes = new BABYLON.SmartArray(256);
  19180. _this._globalPosition = BABYLON.Vector3.Zero();
  19181. _this._refreshFrustumPlanes = true;
  19182. _this.getScene().addCamera(_this);
  19183. if (!_this.getScene().activeCamera) {
  19184. _this.getScene().activeCamera = _this;
  19185. }
  19186. _this.position = position;
  19187. return _this;
  19188. }
  19189. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19190. get: function () {
  19191. return Camera._PERSPECTIVE_CAMERA;
  19192. },
  19193. enumerable: true,
  19194. configurable: true
  19195. });
  19196. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19197. get: function () {
  19198. return Camera._ORTHOGRAPHIC_CAMERA;
  19199. },
  19200. enumerable: true,
  19201. configurable: true
  19202. });
  19203. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19204. /**
  19205. * This is the default FOV mode for perspective cameras.
  19206. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19207. *
  19208. */
  19209. get: function () {
  19210. return Camera._FOVMODE_VERTICAL_FIXED;
  19211. },
  19212. enumerable: true,
  19213. configurable: true
  19214. });
  19215. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19216. /**
  19217. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19218. *
  19219. */
  19220. get: function () {
  19221. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19222. },
  19223. enumerable: true,
  19224. configurable: true
  19225. });
  19226. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19227. get: function () {
  19228. return Camera._RIG_MODE_NONE;
  19229. },
  19230. enumerable: true,
  19231. configurable: true
  19232. });
  19233. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19234. get: function () {
  19235. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19236. },
  19237. enumerable: true,
  19238. configurable: true
  19239. });
  19240. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19241. get: function () {
  19242. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19243. },
  19244. enumerable: true,
  19245. configurable: true
  19246. });
  19247. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19248. get: function () {
  19249. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19250. },
  19251. enumerable: true,
  19252. configurable: true
  19253. });
  19254. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19255. get: function () {
  19256. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19257. },
  19258. enumerable: true,
  19259. configurable: true
  19260. });
  19261. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19262. get: function () {
  19263. return Camera._RIG_MODE_VR;
  19264. },
  19265. enumerable: true,
  19266. configurable: true
  19267. });
  19268. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19269. get: function () {
  19270. return Camera._RIG_MODE_WEBVR;
  19271. },
  19272. enumerable: true,
  19273. configurable: true
  19274. });
  19275. /**
  19276. * Store current camera state (fov, position, etc..)
  19277. */
  19278. Camera.prototype.storeState = function () {
  19279. this._stateStored = true;
  19280. this._storedFov = this.fov;
  19281. return this;
  19282. };
  19283. /**
  19284. * Restores the camera state values if it has been stored. You must call storeState() first
  19285. */
  19286. Camera.prototype._restoreStateValues = function () {
  19287. if (!this._stateStored) {
  19288. return false;
  19289. }
  19290. this.fov = this._storedFov;
  19291. return true;
  19292. };
  19293. /**
  19294. * Restored camera state. You must call storeState() first
  19295. */
  19296. Camera.prototype.restoreState = function () {
  19297. if (this._restoreStateValues()) {
  19298. this.onRestoreStateObservable.notifyObservers(this);
  19299. return true;
  19300. }
  19301. return false;
  19302. };
  19303. Camera.prototype.getClassName = function () {
  19304. return "Camera";
  19305. };
  19306. /**
  19307. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19308. */
  19309. Camera.prototype.toString = function (fullDetails) {
  19310. var ret = "Name: " + this.name;
  19311. ret += ", type: " + this.getClassName();
  19312. if (this.animations) {
  19313. for (var i = 0; i < this.animations.length; i++) {
  19314. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19315. }
  19316. }
  19317. if (fullDetails) {
  19318. }
  19319. return ret;
  19320. };
  19321. Object.defineProperty(Camera.prototype, "globalPosition", {
  19322. get: function () {
  19323. return this._globalPosition;
  19324. },
  19325. enumerable: true,
  19326. configurable: true
  19327. });
  19328. Camera.prototype.getActiveMeshes = function () {
  19329. return this._activeMeshes;
  19330. };
  19331. Camera.prototype.isActiveMesh = function (mesh) {
  19332. return (this._activeMeshes.indexOf(mesh) !== -1);
  19333. };
  19334. //Cache
  19335. Camera.prototype._initCache = function () {
  19336. _super.prototype._initCache.call(this);
  19337. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19338. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19339. this._cache.mode = undefined;
  19340. this._cache.minZ = undefined;
  19341. this._cache.maxZ = undefined;
  19342. this._cache.fov = undefined;
  19343. this._cache.fovMode = undefined;
  19344. this._cache.aspectRatio = undefined;
  19345. this._cache.orthoLeft = undefined;
  19346. this._cache.orthoRight = undefined;
  19347. this._cache.orthoBottom = undefined;
  19348. this._cache.orthoTop = undefined;
  19349. this._cache.renderWidth = undefined;
  19350. this._cache.renderHeight = undefined;
  19351. };
  19352. Camera.prototype._updateCache = function (ignoreParentClass) {
  19353. if (!ignoreParentClass) {
  19354. _super.prototype._updateCache.call(this);
  19355. }
  19356. this._cache.position.copyFrom(this.position);
  19357. this._cache.upVector.copyFrom(this.upVector);
  19358. };
  19359. // Synchronized
  19360. Camera.prototype._isSynchronized = function () {
  19361. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19362. };
  19363. Camera.prototype._isSynchronizedViewMatrix = function () {
  19364. if (!_super.prototype._isSynchronized.call(this))
  19365. return false;
  19366. return this._cache.position.equals(this.position)
  19367. && this._cache.upVector.equals(this.upVector)
  19368. && this.isSynchronizedWithParent();
  19369. };
  19370. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19371. var check = this._cache.mode === this.mode
  19372. && this._cache.minZ === this.minZ
  19373. && this._cache.maxZ === this.maxZ;
  19374. if (!check) {
  19375. return false;
  19376. }
  19377. var engine = this.getEngine();
  19378. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19379. check = this._cache.fov === this.fov
  19380. && this._cache.fovMode === this.fovMode
  19381. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19382. }
  19383. else {
  19384. check = this._cache.orthoLeft === this.orthoLeft
  19385. && this._cache.orthoRight === this.orthoRight
  19386. && this._cache.orthoBottom === this.orthoBottom
  19387. && this._cache.orthoTop === this.orthoTop
  19388. && this._cache.renderWidth === engine.getRenderWidth()
  19389. && this._cache.renderHeight === engine.getRenderHeight();
  19390. }
  19391. return check;
  19392. };
  19393. // Controls
  19394. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19395. };
  19396. Camera.prototype.detachControl = function (element) {
  19397. };
  19398. Camera.prototype.update = function () {
  19399. this._checkInputs();
  19400. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19401. this._updateRigCameras();
  19402. }
  19403. };
  19404. Camera.prototype._checkInputs = function () {
  19405. this.onAfterCheckInputsObservable.notifyObservers(this);
  19406. };
  19407. Object.defineProperty(Camera.prototype, "rigCameras", {
  19408. get: function () {
  19409. return this._rigCameras;
  19410. },
  19411. enumerable: true,
  19412. configurable: true
  19413. });
  19414. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19415. get: function () {
  19416. return this._rigPostProcess;
  19417. },
  19418. enumerable: true,
  19419. configurable: true
  19420. });
  19421. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19422. // invalidate framebuffer
  19423. if (this._postProcesses.length > 0) {
  19424. this._postProcesses[0].markTextureDirty();
  19425. }
  19426. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19427. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19428. var cam = this._rigCameras[i];
  19429. var rigPostProcess = cam._rigPostProcess;
  19430. // for VR rig, there does not have to be a post process
  19431. if (rigPostProcess) {
  19432. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19433. if (isPass) {
  19434. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19435. cam.isIntermediate = this._postProcesses.length === 0;
  19436. }
  19437. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19438. rigPostProcess.markTextureDirty();
  19439. }
  19440. else {
  19441. cam._postProcesses = this._postProcesses.slice(0);
  19442. }
  19443. }
  19444. };
  19445. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19446. if (insertAt === void 0) { insertAt = null; }
  19447. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19448. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19449. return 0;
  19450. }
  19451. if (insertAt == null || insertAt < 0) {
  19452. this._postProcesses.push(postProcess);
  19453. }
  19454. else {
  19455. this._postProcesses.splice(insertAt, 0, postProcess);
  19456. }
  19457. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19458. return this._postProcesses.indexOf(postProcess);
  19459. };
  19460. Camera.prototype.detachPostProcess = function (postProcess) {
  19461. var idx = this._postProcesses.indexOf(postProcess);
  19462. if (idx !== -1) {
  19463. this._postProcesses.splice(idx, 1);
  19464. }
  19465. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19466. };
  19467. Camera.prototype.getWorldMatrix = function () {
  19468. if (!this._worldMatrix) {
  19469. this._worldMatrix = BABYLON.Matrix.Identity();
  19470. }
  19471. var viewMatrix = this.getViewMatrix();
  19472. viewMatrix.invertToRef(this._worldMatrix);
  19473. return this._worldMatrix;
  19474. };
  19475. Camera.prototype._getViewMatrix = function () {
  19476. return BABYLON.Matrix.Identity();
  19477. };
  19478. Camera.prototype.getViewMatrix = function (force) {
  19479. if (!force && this._isSynchronizedViewMatrix()) {
  19480. return this._computedViewMatrix;
  19481. }
  19482. this.updateCache();
  19483. this._computedViewMatrix = this._getViewMatrix();
  19484. this._currentRenderId = this.getScene().getRenderId();
  19485. this._refreshFrustumPlanes = true;
  19486. if (!this.parent || !this.parent.getWorldMatrix) {
  19487. this._globalPosition.copyFrom(this.position);
  19488. }
  19489. else {
  19490. if (!this._worldMatrix) {
  19491. this._worldMatrix = BABYLON.Matrix.Identity();
  19492. }
  19493. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19494. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19495. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19496. this._computedViewMatrix.invert();
  19497. this._markSyncedWithParent();
  19498. }
  19499. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19500. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19501. }
  19502. this.onViewMatrixChangedObservable.notifyObservers(this);
  19503. return this._computedViewMatrix;
  19504. };
  19505. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19506. this._doNotComputeProjectionMatrix = true;
  19507. if (projection !== undefined) {
  19508. this._projectionMatrix = projection;
  19509. }
  19510. };
  19511. ;
  19512. Camera.prototype.unfreezeProjectionMatrix = function () {
  19513. this._doNotComputeProjectionMatrix = false;
  19514. };
  19515. ;
  19516. Camera.prototype.getProjectionMatrix = function (force) {
  19517. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19518. return this._projectionMatrix;
  19519. }
  19520. // Cache
  19521. this._cache.mode = this.mode;
  19522. this._cache.minZ = this.minZ;
  19523. this._cache.maxZ = this.maxZ;
  19524. // Matrix
  19525. this._refreshFrustumPlanes = true;
  19526. var engine = this.getEngine();
  19527. var scene = this.getScene();
  19528. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19529. this._cache.fov = this.fov;
  19530. this._cache.fovMode = this.fovMode;
  19531. this._cache.aspectRatio = engine.getAspectRatio(this);
  19532. if (this.minZ <= 0) {
  19533. this.minZ = 0.1;
  19534. }
  19535. if (scene.useRightHandedSystem) {
  19536. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19537. }
  19538. else {
  19539. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19540. }
  19541. }
  19542. else {
  19543. var halfWidth = engine.getRenderWidth() / 2.0;
  19544. var halfHeight = engine.getRenderHeight() / 2.0;
  19545. if (scene.useRightHandedSystem) {
  19546. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19547. }
  19548. else {
  19549. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19550. }
  19551. this._cache.orthoLeft = this.orthoLeft;
  19552. this._cache.orthoRight = this.orthoRight;
  19553. this._cache.orthoBottom = this.orthoBottom;
  19554. this._cache.orthoTop = this.orthoTop;
  19555. this._cache.renderWidth = engine.getRenderWidth();
  19556. this._cache.renderHeight = engine.getRenderHeight();
  19557. }
  19558. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19559. return this._projectionMatrix;
  19560. };
  19561. Camera.prototype.getTranformationMatrix = function () {
  19562. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19563. return this._transformMatrix;
  19564. };
  19565. Camera.prototype.updateFrustumPlanes = function () {
  19566. if (!this._refreshFrustumPlanes) {
  19567. return;
  19568. }
  19569. this.getTranformationMatrix();
  19570. if (!this._frustumPlanes) {
  19571. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19572. }
  19573. else {
  19574. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19575. }
  19576. this._refreshFrustumPlanes = false;
  19577. };
  19578. Camera.prototype.isInFrustum = function (target) {
  19579. this.updateFrustumPlanes();
  19580. return target.isInFrustum(this._frustumPlanes);
  19581. };
  19582. Camera.prototype.isCompletelyInFrustum = function (target) {
  19583. this.updateFrustumPlanes();
  19584. return target.isCompletelyInFrustum(this._frustumPlanes);
  19585. };
  19586. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19587. if (length === void 0) { length = 100; }
  19588. if (!transform) {
  19589. transform = this.getWorldMatrix();
  19590. }
  19591. if (!origin) {
  19592. origin = this.position;
  19593. }
  19594. var forward = new BABYLON.Vector3(0, 0, 1);
  19595. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19596. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19597. return new BABYLON.Ray(origin, direction, length);
  19598. };
  19599. Camera.prototype.dispose = function () {
  19600. // Observables
  19601. this.onViewMatrixChangedObservable.clear();
  19602. this.onProjectionMatrixChangedObservable.clear();
  19603. this.onAfterCheckInputsObservable.clear();
  19604. this.onRestoreStateObservable.clear();
  19605. // Inputs
  19606. if (this.inputs) {
  19607. this.inputs.clear();
  19608. }
  19609. // Animations
  19610. this.getScene().stopAnimation(this);
  19611. // Remove from scene
  19612. this.getScene().removeCamera(this);
  19613. while (this._rigCameras.length > 0) {
  19614. var camera = this._rigCameras.pop();
  19615. if (camera) {
  19616. camera.dispose();
  19617. }
  19618. }
  19619. // Postprocesses
  19620. if (this._rigPostProcess) {
  19621. this._rigPostProcess.dispose(this);
  19622. this._rigPostProcess = null;
  19623. this._postProcesses = [];
  19624. }
  19625. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19626. this._rigPostProcess = null;
  19627. this._postProcesses = [];
  19628. }
  19629. else {
  19630. var i = this._postProcesses.length;
  19631. while (--i >= 0) {
  19632. this._postProcesses[i].dispose(this);
  19633. }
  19634. }
  19635. // Render targets
  19636. var i = this.customRenderTargets.length;
  19637. while (--i >= 0) {
  19638. this.customRenderTargets[i].dispose();
  19639. }
  19640. this.customRenderTargets = [];
  19641. // Active Meshes
  19642. this._activeMeshes.dispose();
  19643. _super.prototype.dispose.call(this);
  19644. };
  19645. Object.defineProperty(Camera.prototype, "leftCamera", {
  19646. // ---- Camera rigs section ----
  19647. get: function () {
  19648. if (this._rigCameras.length < 1) {
  19649. return null;
  19650. }
  19651. return this._rigCameras[0];
  19652. },
  19653. enumerable: true,
  19654. configurable: true
  19655. });
  19656. Object.defineProperty(Camera.prototype, "rightCamera", {
  19657. get: function () {
  19658. if (this._rigCameras.length < 2) {
  19659. return null;
  19660. }
  19661. return this._rigCameras[1];
  19662. },
  19663. enumerable: true,
  19664. configurable: true
  19665. });
  19666. Camera.prototype.getLeftTarget = function () {
  19667. if (this._rigCameras.length < 1) {
  19668. return null;
  19669. }
  19670. return this._rigCameras[0].getTarget();
  19671. };
  19672. Camera.prototype.getRightTarget = function () {
  19673. if (this._rigCameras.length < 2) {
  19674. return null;
  19675. }
  19676. return this._rigCameras[1].getTarget();
  19677. };
  19678. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19679. if (this.cameraRigMode === mode) {
  19680. return;
  19681. }
  19682. while (this._rigCameras.length > 0) {
  19683. var camera = this._rigCameras.pop();
  19684. if (camera) {
  19685. camera.dispose();
  19686. }
  19687. }
  19688. this.cameraRigMode = mode;
  19689. this._cameraRigParams = {};
  19690. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19691. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19692. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19693. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19694. // create the rig cameras, unless none
  19695. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19696. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19697. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19698. if (leftCamera && rightCamera) {
  19699. this._rigCameras.push(leftCamera);
  19700. this._rigCameras.push(rightCamera);
  19701. }
  19702. }
  19703. switch (this.cameraRigMode) {
  19704. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19705. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19706. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19707. break;
  19708. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19709. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19710. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19711. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19712. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19713. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19714. break;
  19715. case Camera.RIG_MODE_VR:
  19716. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19717. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19718. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19719. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19720. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19721. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19722. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19723. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19724. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19725. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19726. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19727. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19728. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19729. if (metrics.compensateDistortion) {
  19730. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19731. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19732. }
  19733. break;
  19734. case Camera.RIG_MODE_WEBVR:
  19735. if (rigParams.vrDisplay) {
  19736. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19737. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19738. //Left eye
  19739. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19740. this._rigCameras[0].setCameraRigParameter("left", true);
  19741. //leaving this for future reference
  19742. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19743. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19744. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19745. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19746. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19747. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19748. this._rigCameras[0].parent = this;
  19749. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19750. //Right eye
  19751. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19752. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19753. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19754. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19755. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19756. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19757. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19758. this._rigCameras[1].parent = this;
  19759. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19760. if (Camera.UseAlternateWebVRRendering) {
  19761. this._rigCameras[1]._skipRendering = true;
  19762. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19763. }
  19764. }
  19765. break;
  19766. }
  19767. this._cascadePostProcessesToRigCams();
  19768. this.update();
  19769. };
  19770. Camera.prototype._getVRProjectionMatrix = function () {
  19771. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19772. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19773. return this._projectionMatrix;
  19774. };
  19775. Camera.prototype._updateCameraRotationMatrix = function () {
  19776. //Here for WebVR
  19777. };
  19778. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19779. //Here for WebVR
  19780. };
  19781. /**
  19782. * This function MUST be overwritten by the different WebVR cameras available.
  19783. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19784. */
  19785. Camera.prototype._getWebVRProjectionMatrix = function () {
  19786. return BABYLON.Matrix.Identity();
  19787. };
  19788. /**
  19789. * This function MUST be overwritten by the different WebVR cameras available.
  19790. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19791. */
  19792. Camera.prototype._getWebVRViewMatrix = function () {
  19793. return BABYLON.Matrix.Identity();
  19794. };
  19795. Camera.prototype.setCameraRigParameter = function (name, value) {
  19796. if (!this._cameraRigParams) {
  19797. this._cameraRigParams = {};
  19798. }
  19799. this._cameraRigParams[name] = value;
  19800. //provisionnally:
  19801. if (name === "interaxialDistance") {
  19802. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19803. }
  19804. };
  19805. /**
  19806. * needs to be overridden by children so sub has required properties to be copied
  19807. */
  19808. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19809. return null;
  19810. };
  19811. /**
  19812. * May need to be overridden by children
  19813. */
  19814. Camera.prototype._updateRigCameras = function () {
  19815. for (var i = 0; i < this._rigCameras.length; i++) {
  19816. this._rigCameras[i].minZ = this.minZ;
  19817. this._rigCameras[i].maxZ = this.maxZ;
  19818. this._rigCameras[i].fov = this.fov;
  19819. }
  19820. // only update viewport when ANAGLYPH
  19821. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19822. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19823. }
  19824. };
  19825. Camera.prototype._setupInputs = function () {
  19826. };
  19827. Camera.prototype.serialize = function () {
  19828. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19829. // Type
  19830. serializationObject.type = this.getClassName();
  19831. // Parent
  19832. if (this.parent) {
  19833. serializationObject.parentId = this.parent.id;
  19834. }
  19835. if (this.inputs) {
  19836. this.inputs.serialize(serializationObject);
  19837. }
  19838. // Animations
  19839. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19840. serializationObject.ranges = this.serializeAnimationRanges();
  19841. return serializationObject;
  19842. };
  19843. Camera.prototype.clone = function (name) {
  19844. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19845. };
  19846. Camera.prototype.getDirection = function (localAxis) {
  19847. var result = BABYLON.Vector3.Zero();
  19848. this.getDirectionToRef(localAxis, result);
  19849. return result;
  19850. };
  19851. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19852. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19853. };
  19854. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19855. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19856. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19857. switch (type) {
  19858. case "ArcRotateCamera":
  19859. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19860. case "DeviceOrientationCamera":
  19861. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19862. case "FollowCamera":
  19863. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19864. case "ArcFollowCamera":
  19865. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19866. case "GamepadCamera":
  19867. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19868. case "TouchCamera":
  19869. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19870. case "VirtualJoysticksCamera":
  19871. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19872. case "WebVRFreeCamera":
  19873. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19874. case "WebVRGamepadCamera":
  19875. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19876. case "VRDeviceOrientationFreeCamera":
  19877. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19878. case "VRDeviceOrientationGamepadCamera":
  19879. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19880. case "AnaglyphArcRotateCamera":
  19881. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19882. case "AnaglyphFreeCamera":
  19883. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19884. case "AnaglyphGamepadCamera":
  19885. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19886. case "AnaglyphUniversalCamera":
  19887. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19888. case "StereoscopicArcRotateCamera":
  19889. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19890. case "StereoscopicFreeCamera":
  19891. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19892. case "StereoscopicGamepadCamera":
  19893. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19894. case "StereoscopicUniversalCamera":
  19895. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19896. case "FreeCamera":// Forcing Universal here
  19897. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19898. default:// Universal Camera is the default value
  19899. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19900. }
  19901. };
  19902. Camera.prototype.computeWorldMatrix = function () {
  19903. return this.getWorldMatrix();
  19904. };
  19905. Camera.Parse = function (parsedCamera, scene) {
  19906. var type = parsedCamera.type;
  19907. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  19908. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  19909. // Parent
  19910. if (parsedCamera.parentId) {
  19911. camera._waitingParentId = parsedCamera.parentId;
  19912. }
  19913. //If camera has an input manager, let it parse inputs settings
  19914. if (camera.inputs) {
  19915. camera.inputs.parse(parsedCamera);
  19916. camera._setupInputs();
  19917. }
  19918. if (camera.setPosition) {
  19919. camera.position.copyFromFloats(0, 0, 0);
  19920. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  19921. }
  19922. // Target
  19923. if (parsedCamera.target) {
  19924. if (camera.setTarget) {
  19925. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19926. }
  19927. }
  19928. // Apply 3d rig, when found
  19929. if (parsedCamera.cameraRigMode) {
  19930. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19931. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19932. }
  19933. // Animations
  19934. if (parsedCamera.animations) {
  19935. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19936. var parsedAnimation = parsedCamera.animations[animationIndex];
  19937. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19938. }
  19939. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  19940. }
  19941. if (parsedCamera.autoAnimate) {
  19942. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  19943. }
  19944. return camera;
  19945. };
  19946. // Statics
  19947. Camera._PERSPECTIVE_CAMERA = 0;
  19948. Camera._ORTHOGRAPHIC_CAMERA = 1;
  19949. Camera._FOVMODE_VERTICAL_FIXED = 0;
  19950. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  19951. Camera._RIG_MODE_NONE = 0;
  19952. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  19953. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  19954. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  19955. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  19956. Camera._RIG_MODE_VR = 20;
  19957. Camera._RIG_MODE_WEBVR = 21;
  19958. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  19959. Camera.UseAlternateWebVRRendering = false;
  19960. __decorate([
  19961. BABYLON.serializeAsVector3()
  19962. ], Camera.prototype, "position", void 0);
  19963. __decorate([
  19964. BABYLON.serializeAsVector3()
  19965. ], Camera.prototype, "upVector", void 0);
  19966. __decorate([
  19967. BABYLON.serialize()
  19968. ], Camera.prototype, "orthoLeft", void 0);
  19969. __decorate([
  19970. BABYLON.serialize()
  19971. ], Camera.prototype, "orthoRight", void 0);
  19972. __decorate([
  19973. BABYLON.serialize()
  19974. ], Camera.prototype, "orthoBottom", void 0);
  19975. __decorate([
  19976. BABYLON.serialize()
  19977. ], Camera.prototype, "orthoTop", void 0);
  19978. __decorate([
  19979. BABYLON.serialize()
  19980. ], Camera.prototype, "fov", void 0);
  19981. __decorate([
  19982. BABYLON.serialize()
  19983. ], Camera.prototype, "minZ", void 0);
  19984. __decorate([
  19985. BABYLON.serialize()
  19986. ], Camera.prototype, "maxZ", void 0);
  19987. __decorate([
  19988. BABYLON.serialize()
  19989. ], Camera.prototype, "inertia", void 0);
  19990. __decorate([
  19991. BABYLON.serialize()
  19992. ], Camera.prototype, "mode", void 0);
  19993. __decorate([
  19994. BABYLON.serialize()
  19995. ], Camera.prototype, "layerMask", void 0);
  19996. __decorate([
  19997. BABYLON.serialize()
  19998. ], Camera.prototype, "fovMode", void 0);
  19999. __decorate([
  20000. BABYLON.serialize()
  20001. ], Camera.prototype, "cameraRigMode", void 0);
  20002. __decorate([
  20003. BABYLON.serialize()
  20004. ], Camera.prototype, "interaxialDistance", void 0);
  20005. __decorate([
  20006. BABYLON.serialize()
  20007. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20008. return Camera;
  20009. }(BABYLON.Node));
  20010. BABYLON.Camera = Camera;
  20011. })(BABYLON || (BABYLON = {}));
  20012. //# sourceMappingURL=babylon.camera.js.map
  20013. var BABYLON;
  20014. (function (BABYLON) {
  20015. var RenderingManager = /** @class */ (function () {
  20016. function RenderingManager(scene) {
  20017. this._renderingGroups = new Array();
  20018. this._autoClearDepthStencil = {};
  20019. this._customOpaqueSortCompareFn = {};
  20020. this._customAlphaTestSortCompareFn = {};
  20021. this._customTransparentSortCompareFn = {};
  20022. this._renderinGroupInfo = null;
  20023. this._scene = scene;
  20024. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20025. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20026. }
  20027. }
  20028. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20029. if (depth === void 0) { depth = true; }
  20030. if (stencil === void 0) { stencil = true; }
  20031. if (this._depthStencilBufferAlreadyCleaned) {
  20032. return;
  20033. }
  20034. this._scene.getEngine().clear(null, false, depth, stencil);
  20035. this._depthStencilBufferAlreadyCleaned = true;
  20036. };
  20037. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20038. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20039. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20040. var info = null;
  20041. if (observable) {
  20042. if (!this._renderinGroupInfo) {
  20043. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20044. }
  20045. info = this._renderinGroupInfo;
  20046. info.scene = this._scene;
  20047. info.camera = this._scene.activeCamera;
  20048. }
  20049. // Dispatch sprites
  20050. if (renderSprites) {
  20051. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20052. var manager = this._scene.spriteManagers[index];
  20053. this.dispatchSprites(manager);
  20054. }
  20055. }
  20056. // Render
  20057. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20058. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20059. var renderingGroup = this._renderingGroups[index];
  20060. if (!renderingGroup && !observable)
  20061. continue;
  20062. var renderingGroupMask = 0;
  20063. // Fire PRECLEAR stage
  20064. if (observable && info) {
  20065. renderingGroupMask = Math.pow(2, index);
  20066. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20067. info.renderingGroupId = index;
  20068. observable.notifyObservers(info, renderingGroupMask);
  20069. }
  20070. // Clear depth/stencil if needed
  20071. if (RenderingManager.AUTOCLEAR) {
  20072. var autoClear = this._autoClearDepthStencil[index];
  20073. if (autoClear && autoClear.autoClear) {
  20074. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20075. }
  20076. }
  20077. if (observable && info) {
  20078. // Fire PREOPAQUE stage
  20079. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20080. observable.notifyObservers(info, renderingGroupMask);
  20081. // Fire PRETRANSPARENT stage
  20082. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20083. observable.notifyObservers(info, renderingGroupMask);
  20084. }
  20085. if (renderingGroup)
  20086. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20087. // Fire POSTTRANSPARENT stage
  20088. if (observable && info) {
  20089. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20090. observable.notifyObservers(info, renderingGroupMask);
  20091. }
  20092. }
  20093. };
  20094. RenderingManager.prototype.reset = function () {
  20095. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20096. var renderingGroup = this._renderingGroups[index];
  20097. if (renderingGroup) {
  20098. renderingGroup.prepare();
  20099. }
  20100. }
  20101. };
  20102. RenderingManager.prototype.dispose = function () {
  20103. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20104. var renderingGroup = this._renderingGroups[index];
  20105. if (renderingGroup) {
  20106. renderingGroup.dispose();
  20107. }
  20108. }
  20109. this._renderingGroups.length = 0;
  20110. };
  20111. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20112. if (this._renderingGroups[renderingGroupId] === undefined) {
  20113. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20114. }
  20115. };
  20116. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20117. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20118. this._prepareRenderingGroup(renderingGroupId);
  20119. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20120. };
  20121. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20122. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20123. this._prepareRenderingGroup(renderingGroupId);
  20124. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20125. };
  20126. /**
  20127. * @param subMesh The submesh to dispatch
  20128. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20129. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20130. */
  20131. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20132. if (mesh === undefined) {
  20133. mesh = subMesh.getMesh();
  20134. }
  20135. var renderingGroupId = mesh.renderingGroupId || 0;
  20136. this._prepareRenderingGroup(renderingGroupId);
  20137. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20138. };
  20139. /**
  20140. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20141. * This allowed control for front to back rendering or reversly depending of the special needs.
  20142. *
  20143. * @param renderingGroupId The rendering group id corresponding to its index
  20144. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20145. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20146. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20147. */
  20148. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20149. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20150. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20151. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20152. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20153. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20154. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20155. if (this._renderingGroups[renderingGroupId]) {
  20156. var group = this._renderingGroups[renderingGroupId];
  20157. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20158. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20159. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20160. }
  20161. };
  20162. /**
  20163. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20164. *
  20165. * @param renderingGroupId The rendering group id corresponding to its index
  20166. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20167. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20168. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20169. */
  20170. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20171. if (depth === void 0) { depth = true; }
  20172. if (stencil === void 0) { stencil = true; }
  20173. this._autoClearDepthStencil[renderingGroupId] = {
  20174. autoClear: autoClearDepthStencil,
  20175. depth: depth,
  20176. stencil: stencil
  20177. };
  20178. };
  20179. /**
  20180. * The max id used for rendering groups (not included)
  20181. */
  20182. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20183. /**
  20184. * The min id used for rendering groups (included)
  20185. */
  20186. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20187. /**
  20188. * Used to globally prevent autoclearing scenes.
  20189. */
  20190. RenderingManager.AUTOCLEAR = true;
  20191. return RenderingManager;
  20192. }());
  20193. BABYLON.RenderingManager = RenderingManager;
  20194. })(BABYLON || (BABYLON = {}));
  20195. //# sourceMappingURL=babylon.renderingManager.js.map
  20196. var BABYLON;
  20197. (function (BABYLON) {
  20198. var RenderingGroup = /** @class */ (function () {
  20199. /**
  20200. * Creates a new rendering group.
  20201. * @param index The rendering group index
  20202. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20203. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20204. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20205. */
  20206. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20207. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20208. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20209. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20210. this.index = index;
  20211. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20212. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20213. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20214. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20215. this._particleSystems = new BABYLON.SmartArray(256);
  20216. this._spriteManagers = new BABYLON.SmartArray(256);
  20217. this._edgesRenderers = new BABYLON.SmartArray(16);
  20218. this._scene = scene;
  20219. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20220. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20221. this.transparentSortCompareFn = transparentSortCompareFn;
  20222. }
  20223. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20224. /**
  20225. * Set the opaque sort comparison function.
  20226. * If null the sub meshes will be render in the order they were created
  20227. */
  20228. set: function (value) {
  20229. this._opaqueSortCompareFn = value;
  20230. if (value) {
  20231. this._renderOpaque = this.renderOpaqueSorted;
  20232. }
  20233. else {
  20234. this._renderOpaque = RenderingGroup.renderUnsorted;
  20235. }
  20236. },
  20237. enumerable: true,
  20238. configurable: true
  20239. });
  20240. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20241. /**
  20242. * Set the alpha test sort comparison function.
  20243. * If null the sub meshes will be render in the order they were created
  20244. */
  20245. set: function (value) {
  20246. this._alphaTestSortCompareFn = value;
  20247. if (value) {
  20248. this._renderAlphaTest = this.renderAlphaTestSorted;
  20249. }
  20250. else {
  20251. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20252. }
  20253. },
  20254. enumerable: true,
  20255. configurable: true
  20256. });
  20257. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20258. /**
  20259. * Set the transparent sort comparison function.
  20260. * If null the sub meshes will be render in the order they were created
  20261. */
  20262. set: function (value) {
  20263. if (value) {
  20264. this._transparentSortCompareFn = value;
  20265. }
  20266. else {
  20267. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20268. }
  20269. this._renderTransparent = this.renderTransparentSorted;
  20270. },
  20271. enumerable: true,
  20272. configurable: true
  20273. });
  20274. /**
  20275. * Render all the sub meshes contained in the group.
  20276. * @param customRenderFunction Used to override the default render behaviour of the group.
  20277. * @returns true if rendered some submeshes.
  20278. */
  20279. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20280. if (customRenderFunction) {
  20281. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20282. return;
  20283. }
  20284. var engine = this._scene.getEngine();
  20285. // Depth only
  20286. if (this._depthOnlySubMeshes.length !== 0) {
  20287. engine.setColorWrite(false);
  20288. this._renderAlphaTest(this._depthOnlySubMeshes);
  20289. engine.setColorWrite(true);
  20290. }
  20291. // Opaque
  20292. if (this._opaqueSubMeshes.length !== 0) {
  20293. this._renderOpaque(this._opaqueSubMeshes);
  20294. }
  20295. // Alpha test
  20296. if (this._alphaTestSubMeshes.length !== 0) {
  20297. this._renderAlphaTest(this._alphaTestSubMeshes);
  20298. }
  20299. var stencilState = engine.getStencilBuffer();
  20300. engine.setStencilBuffer(false);
  20301. // Sprites
  20302. if (renderSprites) {
  20303. this._renderSprites();
  20304. }
  20305. // Particles
  20306. if (renderParticles) {
  20307. this._renderParticles(activeMeshes);
  20308. }
  20309. if (this.onBeforeTransparentRendering) {
  20310. this.onBeforeTransparentRendering();
  20311. }
  20312. // Transparent
  20313. if (this._transparentSubMeshes.length !== 0) {
  20314. this._renderTransparent(this._transparentSubMeshes);
  20315. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20316. }
  20317. // Set back stencil to false in case it changes before the edge renderer.
  20318. engine.setStencilBuffer(false);
  20319. // Edges
  20320. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20321. this._edgesRenderers.data[edgesRendererIndex].render();
  20322. }
  20323. // Restore Stencil state.
  20324. engine.setStencilBuffer(stencilState);
  20325. };
  20326. /**
  20327. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20328. * @param subMeshes The submeshes to render
  20329. */
  20330. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20331. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20332. };
  20333. /**
  20334. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20335. * @param subMeshes The submeshes to render
  20336. */
  20337. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20338. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20339. };
  20340. /**
  20341. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20342. * @param subMeshes The submeshes to render
  20343. */
  20344. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20345. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20346. };
  20347. /**
  20348. * Renders the submeshes in a specified order.
  20349. * @param subMeshes The submeshes to sort before render
  20350. * @param sortCompareFn The comparison function use to sort
  20351. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20352. * @param transparent Specifies to activate blending if true
  20353. */
  20354. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20355. var subIndex = 0;
  20356. var subMesh;
  20357. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20358. for (; subIndex < subMeshes.length; subIndex++) {
  20359. subMesh = subMeshes.data[subIndex];
  20360. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20361. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20362. }
  20363. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20364. if (sortCompareFn) {
  20365. sortedArray.sort(sortCompareFn);
  20366. }
  20367. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20368. subMesh = sortedArray[subIndex];
  20369. if (transparent) {
  20370. var material = subMesh.getMaterial();
  20371. if (material && material.needDepthPrePass) {
  20372. var engine = material.getScene().getEngine();
  20373. engine.setColorWrite(false);
  20374. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20375. subMesh.render(false);
  20376. engine.setColorWrite(true);
  20377. }
  20378. }
  20379. subMesh.render(transparent);
  20380. }
  20381. };
  20382. /**
  20383. * Renders the submeshes in the order they were dispatched (no sort applied).
  20384. * @param subMeshes The submeshes to render
  20385. */
  20386. RenderingGroup.renderUnsorted = function (subMeshes) {
  20387. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20388. var submesh = subMeshes.data[subIndex];
  20389. submesh.render(false);
  20390. }
  20391. };
  20392. /**
  20393. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20394. * are rendered back to front if in the same alpha index.
  20395. *
  20396. * @param a The first submesh
  20397. * @param b The second submesh
  20398. * @returns The result of the comparison
  20399. */
  20400. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20401. // Alpha index first
  20402. if (a._alphaIndex > b._alphaIndex) {
  20403. return 1;
  20404. }
  20405. if (a._alphaIndex < b._alphaIndex) {
  20406. return -1;
  20407. }
  20408. // Then distance to camera
  20409. return RenderingGroup.backToFrontSortCompare(a, b);
  20410. };
  20411. /**
  20412. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20413. * are rendered back to front.
  20414. *
  20415. * @param a The first submesh
  20416. * @param b The second submesh
  20417. * @returns The result of the comparison
  20418. */
  20419. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20420. // Then distance to camera
  20421. if (a._distanceToCamera < b._distanceToCamera) {
  20422. return 1;
  20423. }
  20424. if (a._distanceToCamera > b._distanceToCamera) {
  20425. return -1;
  20426. }
  20427. return 0;
  20428. };
  20429. /**
  20430. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20431. * are rendered front to back (prevent overdraw).
  20432. *
  20433. * @param a The first submesh
  20434. * @param b The second submesh
  20435. * @returns The result of the comparison
  20436. */
  20437. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20438. // Then distance to camera
  20439. if (a._distanceToCamera < b._distanceToCamera) {
  20440. return -1;
  20441. }
  20442. if (a._distanceToCamera > b._distanceToCamera) {
  20443. return 1;
  20444. }
  20445. return 0;
  20446. };
  20447. /**
  20448. * Resets the different lists of submeshes to prepare a new frame.
  20449. */
  20450. RenderingGroup.prototype.prepare = function () {
  20451. this._opaqueSubMeshes.reset();
  20452. this._transparentSubMeshes.reset();
  20453. this._alphaTestSubMeshes.reset();
  20454. this._depthOnlySubMeshes.reset();
  20455. this._particleSystems.reset();
  20456. this._spriteManagers.reset();
  20457. this._edgesRenderers.reset();
  20458. };
  20459. RenderingGroup.prototype.dispose = function () {
  20460. this._opaqueSubMeshes.dispose();
  20461. this._transparentSubMeshes.dispose();
  20462. this._alphaTestSubMeshes.dispose();
  20463. this._depthOnlySubMeshes.dispose();
  20464. this._particleSystems.dispose();
  20465. this._spriteManagers.dispose();
  20466. this._edgesRenderers.dispose();
  20467. };
  20468. /**
  20469. * Inserts the submesh in its correct queue depending on its material.
  20470. * @param subMesh The submesh to dispatch
  20471. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20472. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20473. */
  20474. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20475. // Get mesh and materials if not provided
  20476. if (mesh === undefined) {
  20477. mesh = subMesh.getMesh();
  20478. }
  20479. if (material === undefined) {
  20480. material = subMesh.getMaterial();
  20481. }
  20482. if (material === null || material === undefined) {
  20483. return;
  20484. }
  20485. if (material.needAlphaBlendingForMesh(mesh)) {
  20486. this._transparentSubMeshes.push(subMesh);
  20487. }
  20488. else if (material.needAlphaTesting()) {
  20489. if (material.needDepthPrePass) {
  20490. this._depthOnlySubMeshes.push(subMesh);
  20491. }
  20492. this._alphaTestSubMeshes.push(subMesh);
  20493. }
  20494. else {
  20495. if (material.needDepthPrePass) {
  20496. this._depthOnlySubMeshes.push(subMesh);
  20497. }
  20498. this._opaqueSubMeshes.push(subMesh); // Opaque
  20499. }
  20500. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20501. this._edgesRenderers.push(mesh._edgesRenderer);
  20502. }
  20503. };
  20504. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20505. this._spriteManagers.push(spriteManager);
  20506. };
  20507. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20508. this._particleSystems.push(particleSystem);
  20509. };
  20510. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20511. if (this._particleSystems.length === 0) {
  20512. return;
  20513. }
  20514. // Particles
  20515. var activeCamera = this._scene.activeCamera;
  20516. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20517. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  20518. var particleSystem = this._particleSystems.data[particleIndex];
  20519. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20520. continue;
  20521. }
  20522. var emitter = particleSystem.emitter;
  20523. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20524. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20525. }
  20526. }
  20527. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20528. };
  20529. RenderingGroup.prototype._renderSprites = function () {
  20530. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20531. return;
  20532. }
  20533. // Sprites
  20534. var activeCamera = this._scene.activeCamera;
  20535. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20536. for (var id = 0; id < this._spriteManagers.length; id++) {
  20537. var spriteManager = this._spriteManagers.data[id];
  20538. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20539. spriteManager.render();
  20540. }
  20541. }
  20542. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20543. };
  20544. return RenderingGroup;
  20545. }());
  20546. BABYLON.RenderingGroup = RenderingGroup;
  20547. })(BABYLON || (BABYLON = {}));
  20548. //# sourceMappingURL=babylon.renderingGroup.js.map
  20549. var BABYLON;
  20550. (function (BABYLON) {
  20551. var ClickInfo = /** @class */ (function () {
  20552. function ClickInfo() {
  20553. this._singleClick = false;
  20554. this._doubleClick = false;
  20555. this._hasSwiped = false;
  20556. this._ignore = false;
  20557. }
  20558. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20559. get: function () {
  20560. return this._singleClick;
  20561. },
  20562. set: function (b) {
  20563. this._singleClick = b;
  20564. },
  20565. enumerable: true,
  20566. configurable: true
  20567. });
  20568. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20569. get: function () {
  20570. return this._doubleClick;
  20571. },
  20572. set: function (b) {
  20573. this._doubleClick = b;
  20574. },
  20575. enumerable: true,
  20576. configurable: true
  20577. });
  20578. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20579. get: function () {
  20580. return this._hasSwiped;
  20581. },
  20582. set: function (b) {
  20583. this._hasSwiped = b;
  20584. },
  20585. enumerable: true,
  20586. configurable: true
  20587. });
  20588. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20589. get: function () {
  20590. return this._ignore;
  20591. },
  20592. set: function (b) {
  20593. this._ignore = b;
  20594. },
  20595. enumerable: true,
  20596. configurable: true
  20597. });
  20598. return ClickInfo;
  20599. }());
  20600. /**
  20601. * This class is used by the onRenderingGroupObservable
  20602. */
  20603. var RenderingGroupInfo = /** @class */ (function () {
  20604. function RenderingGroupInfo() {
  20605. }
  20606. /**
  20607. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20608. * This stage will be fired no matter what
  20609. */
  20610. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20611. /**
  20612. * Called before opaque object are rendered.
  20613. * This stage will be fired only if there's 3D Opaque content to render
  20614. */
  20615. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20616. /**
  20617. * Called after the opaque objects are rendered and before the transparent ones
  20618. * This stage will be fired only if there's 3D transparent content to render
  20619. */
  20620. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20621. /**
  20622. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20623. * This stage will be fired no matter what
  20624. */
  20625. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20626. return RenderingGroupInfo;
  20627. }());
  20628. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20629. /**
  20630. * Represents a scene to be rendered by the engine.
  20631. * @see http://doc.babylonjs.com/page.php?p=21911
  20632. */
  20633. var Scene = /** @class */ (function () {
  20634. /**
  20635. * @constructor
  20636. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20637. */
  20638. function Scene(engine) {
  20639. // Members
  20640. this.autoClear = true;
  20641. this.autoClearDepthAndStencil = true;
  20642. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20643. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20644. this.forceWireframe = false;
  20645. this._forcePointsCloud = false;
  20646. this.forceShowBoundingBoxes = false;
  20647. this.animationsEnabled = true;
  20648. this.useConstantAnimationDeltaTime = false;
  20649. this.constantlyUpdateMeshUnderPointer = false;
  20650. this.hoverCursor = "pointer";
  20651. this.defaultCursor = "";
  20652. /**
  20653. * This is used to call preventDefault() on pointer down
  20654. * in order to block unwanted artifacts like system double clicks
  20655. */
  20656. this.preventDefaultOnPointerDown = true;
  20657. // Metadata
  20658. this.metadata = null;
  20659. /**
  20660. * An event triggered when the scene is disposed.
  20661. * @type {BABYLON.Observable}
  20662. */
  20663. this.onDisposeObservable = new BABYLON.Observable();
  20664. /**
  20665. * An event triggered before rendering the scene (right after animations and physics)
  20666. * @type {BABYLON.Observable}
  20667. */
  20668. this.onBeforeRenderObservable = new BABYLON.Observable();
  20669. /**
  20670. * An event triggered after rendering the scene
  20671. * @type {BABYLON.Observable}
  20672. */
  20673. this.onAfterRenderObservable = new BABYLON.Observable();
  20674. /**
  20675. * An event triggered before animating the scene
  20676. * @type {BABYLON.Observable}
  20677. */
  20678. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20679. /**
  20680. * An event triggered after animations processing
  20681. * @type {BABYLON.Observable}
  20682. */
  20683. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20684. /**
  20685. * An event triggered before draw calls are ready to be sent
  20686. * @type {BABYLON.Observable}
  20687. */
  20688. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20689. /**
  20690. * An event triggered after draw calls have been sent
  20691. * @type {BABYLON.Observable}
  20692. */
  20693. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20694. /**
  20695. * An event triggered when physic simulation is about to be run
  20696. * @type {BABYLON.Observable}
  20697. */
  20698. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20699. /**
  20700. * An event triggered when physic simulation has been done
  20701. * @type {BABYLON.Observable}
  20702. */
  20703. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20704. /**
  20705. * An event triggered when the scene is ready
  20706. * @type {BABYLON.Observable}
  20707. */
  20708. this.onReadyObservable = new BABYLON.Observable();
  20709. /**
  20710. * An event triggered before rendering a camera
  20711. * @type {BABYLON.Observable}
  20712. */
  20713. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20714. /**
  20715. * An event triggered after rendering a camera
  20716. * @type {BABYLON.Observable}
  20717. */
  20718. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20719. /**
  20720. * An event triggered when active meshes evaluation is about to start
  20721. * @type {BABYLON.Observable}
  20722. */
  20723. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20724. /**
  20725. * An event triggered when active meshes evaluation is done
  20726. * @type {BABYLON.Observable}
  20727. */
  20728. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20729. /**
  20730. * An event triggered when particles rendering is about to start
  20731. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20732. * @type {BABYLON.Observable}
  20733. */
  20734. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20735. /**
  20736. * An event triggered when particles rendering is done
  20737. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20738. * @type {BABYLON.Observable}
  20739. */
  20740. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20741. /**
  20742. * An event triggered when sprites rendering is about to start
  20743. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20744. * @type {BABYLON.Observable}
  20745. */
  20746. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20747. /**
  20748. * An event triggered when sprites rendering is done
  20749. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20750. * @type {BABYLON.Observable}
  20751. */
  20752. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20753. /**
  20754. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20755. * @type {BABYLON.Observable}
  20756. */
  20757. this.onDataLoadedObservable = new BABYLON.Observable();
  20758. /**
  20759. * An event triggered when a camera is created
  20760. * @type {BABYLON.Observable}
  20761. */
  20762. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20763. /**
  20764. * An event triggered when a camera is removed
  20765. * @type {BABYLON.Observable}
  20766. */
  20767. this.onCameraRemovedObservable = new BABYLON.Observable();
  20768. /**
  20769. * An event triggered when a light is created
  20770. * @type {BABYLON.Observable}
  20771. */
  20772. this.onNewLightAddedObservable = new BABYLON.Observable();
  20773. /**
  20774. * An event triggered when a light is removed
  20775. * @type {BABYLON.Observable}
  20776. */
  20777. this.onLightRemovedObservable = new BABYLON.Observable();
  20778. /**
  20779. * An event triggered when a geometry is created
  20780. * @type {BABYLON.Observable}
  20781. */
  20782. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20783. /**
  20784. * An event triggered when a geometry is removed
  20785. * @type {BABYLON.Observable}
  20786. */
  20787. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20788. /**
  20789. * An event triggered when a transform node is created
  20790. * @type {BABYLON.Observable}
  20791. */
  20792. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20793. /**
  20794. * An event triggered when a transform node is removed
  20795. * @type {BABYLON.Observable}
  20796. */
  20797. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20798. /**
  20799. * An event triggered when a mesh is created
  20800. * @type {BABYLON.Observable}
  20801. */
  20802. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20803. /**
  20804. * An event triggered when a mesh is removed
  20805. * @type {BABYLON.Observable}
  20806. */
  20807. this.onMeshRemovedObservable = new BABYLON.Observable();
  20808. /**
  20809. * An event triggered when render targets are about to be rendered
  20810. * Can happen multiple times per frame.
  20811. * @type {BABYLON.Observable}
  20812. */
  20813. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20814. /**
  20815. * An event triggered when render targets were rendered.
  20816. * Can happen multiple times per frame.
  20817. * @type {BABYLON.Observable}
  20818. */
  20819. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20820. /**
  20821. * An event triggered before calculating deterministic simulation step
  20822. * @type {BABYLON.Observable}
  20823. */
  20824. this.onBeforeStepObservable = new BABYLON.Observable();
  20825. /**
  20826. * An event triggered after calculating deterministic simulation step
  20827. * @type {BABYLON.Observable}
  20828. */
  20829. this.onAfterStepObservable = new BABYLON.Observable();
  20830. /**
  20831. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20832. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20833. * 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)
  20834. */
  20835. this.onRenderingGroupObservable = new BABYLON.Observable();
  20836. // Animations
  20837. this.animations = [];
  20838. /**
  20839. * 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).
  20840. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20841. */
  20842. this.onPrePointerObservable = new BABYLON.Observable();
  20843. /**
  20844. * Observable event triggered each time an input event is received from the rendering canvas
  20845. */
  20846. this.onPointerObservable = new BABYLON.Observable();
  20847. this._meshPickProceed = false;
  20848. this._currentPickResult = null;
  20849. this._previousPickResult = null;
  20850. this._totalPointersPressed = 0;
  20851. this._doubleClickOccured = false;
  20852. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20853. this.cameraToUseForPointers = null;
  20854. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20855. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20856. this._startingPointerTime = 0;
  20857. this._previousStartingPointerTime = 0;
  20858. // Deterministic lockstep
  20859. this._timeAccumulator = 0;
  20860. this._currentStepId = 0;
  20861. this._currentInternalStep = 0;
  20862. // Keyboard
  20863. /**
  20864. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20865. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20866. */
  20867. this.onPreKeyboardObservable = new BABYLON.Observable();
  20868. /**
  20869. * Observable event triggered each time an keyboard event is received from the hosting window
  20870. */
  20871. this.onKeyboardObservable = new BABYLON.Observable();
  20872. // Coordinate system
  20873. /**
  20874. * use right-handed coordinate system on this scene.
  20875. * @type {boolean}
  20876. */
  20877. this._useRightHandedSystem = false;
  20878. // Fog
  20879. this._fogEnabled = true;
  20880. this._fogMode = Scene.FOGMODE_NONE;
  20881. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20882. this.fogDensity = 0.1;
  20883. this.fogStart = 0;
  20884. this.fogEnd = 1000.0;
  20885. // Lights
  20886. /**
  20887. * is shadow enabled on this scene.
  20888. * @type {boolean}
  20889. */
  20890. this._shadowsEnabled = true;
  20891. /**
  20892. * is light enabled on this scene.
  20893. * @type {boolean}
  20894. */
  20895. this._lightsEnabled = true;
  20896. /**
  20897. * All of the lights added to this scene.
  20898. * @see BABYLON.Light
  20899. * @type {BABYLON.Light[]}
  20900. */
  20901. this.lights = new Array();
  20902. // Cameras
  20903. /** All of the cameras added to this scene. */
  20904. this.cameras = new Array();
  20905. /** All of the active cameras added to this scene. */
  20906. this.activeCameras = new Array();
  20907. // Meshes
  20908. /**
  20909. * All of the tranform nodes added to this scene.
  20910. * @see BABYLON.TransformNode
  20911. * @type {BABYLON.TransformNode[]}
  20912. */
  20913. this.transformNodes = new Array();
  20914. /**
  20915. * All of the (abstract) meshes added to this scene.
  20916. * @see BABYLON.AbstractMesh
  20917. * @type {BABYLON.AbstractMesh[]}
  20918. */
  20919. this.meshes = new Array();
  20920. /**
  20921. * All of the animation groups added to this scene.
  20922. * @see BABYLON.AnimationGroup
  20923. * @type {BABYLON.AnimationGroup[]}
  20924. */
  20925. this.animationGroups = new Array();
  20926. // Geometries
  20927. this._geometries = new Array();
  20928. this.materials = new Array();
  20929. this.multiMaterials = new Array();
  20930. // Textures
  20931. this._texturesEnabled = true;
  20932. this.textures = new Array();
  20933. // Particles
  20934. this.particlesEnabled = true;
  20935. this.particleSystems = new Array();
  20936. // Sprites
  20937. this.spritesEnabled = true;
  20938. this.spriteManagers = new Array();
  20939. /**
  20940. * The list of layers (background and foreground) of the scene.
  20941. */
  20942. this.layers = new Array();
  20943. /**
  20944. * The list of effect layers (highlights/glow) contained in the scene.
  20945. */
  20946. this.effectLayers = new Array();
  20947. // Skeletons
  20948. this._skeletonsEnabled = true;
  20949. this.skeletons = new Array();
  20950. // Morph targets
  20951. this.morphTargetManagers = new Array();
  20952. // Lens flares
  20953. this.lensFlaresEnabled = true;
  20954. this.lensFlareSystems = new Array();
  20955. // Collisions
  20956. this.collisionsEnabled = true;
  20957. /** Defines the gravity applied to this scene */
  20958. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20959. // Postprocesses
  20960. this.postProcesses = new Array();
  20961. this.postProcessesEnabled = true;
  20962. // Customs render targets
  20963. this.renderTargetsEnabled = true;
  20964. this.dumpNextRenderTargets = false;
  20965. this.customRenderTargets = new Array();
  20966. // Imported meshes
  20967. this.importedMeshesFiles = new Array();
  20968. // Probes
  20969. this.probesEnabled = true;
  20970. this.reflectionProbes = new Array();
  20971. this._actionManagers = new Array();
  20972. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  20973. // Procedural textures
  20974. this.proceduralTexturesEnabled = true;
  20975. this._proceduralTextures = new Array();
  20976. this.soundTracks = new Array();
  20977. this._audioEnabled = true;
  20978. this._headphone = false;
  20979. // Performance counters
  20980. this._totalVertices = new BABYLON.PerfCounter();
  20981. this._activeIndices = new BABYLON.PerfCounter();
  20982. this._activeParticles = new BABYLON.PerfCounter();
  20983. this._activeBones = new BABYLON.PerfCounter();
  20984. this._animationTime = 0;
  20985. this.animationTimeScale = 1;
  20986. this._renderId = 0;
  20987. this._executeWhenReadyTimeoutId = -1;
  20988. this._intermediateRendering = false;
  20989. this._viewUpdateFlag = -1;
  20990. this._projectionUpdateFlag = -1;
  20991. this._alternateViewUpdateFlag = -1;
  20992. this._alternateProjectionUpdateFlag = -1;
  20993. this._toBeDisposed = new BABYLON.SmartArray(256);
  20994. this._activeRequests = new Array();
  20995. this._pendingData = new Array();
  20996. this._isDisposed = false;
  20997. this.dispatchAllSubMeshesOfActiveMeshes = false;
  20998. this._activeMeshes = new BABYLON.SmartArray(256);
  20999. this._processedMaterials = new BABYLON.SmartArray(256);
  21000. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21001. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21002. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21003. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21004. this._activeAnimatables = new Array();
  21005. this._transformMatrix = BABYLON.Matrix.Zero();
  21006. this._useAlternateCameraConfiguration = false;
  21007. this._alternateRendering = false;
  21008. this.requireLightSorting = false;
  21009. this._activeMeshesFrozen = false;
  21010. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21011. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21012. this._engine.scenes.push(this);
  21013. this._uid = null;
  21014. this._renderingManager = new BABYLON.RenderingManager(this);
  21015. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21016. if (BABYLON.OutlineRenderer) {
  21017. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21018. }
  21019. if (BABYLON.Tools.IsWindowObjectExist()) {
  21020. this.attachControl();
  21021. }
  21022. //simplification queue
  21023. if (BABYLON.SimplificationQueue) {
  21024. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21025. }
  21026. //collision coordinator initialization. For now legacy per default.
  21027. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21028. // Uniform Buffer
  21029. this._createUbo();
  21030. // Default Image processing definition.
  21031. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21032. }
  21033. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21034. /** The fog is deactivated */
  21035. get: function () {
  21036. return Scene._FOGMODE_NONE;
  21037. },
  21038. enumerable: true,
  21039. configurable: true
  21040. });
  21041. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21042. /** The fog density is following an exponential function */
  21043. get: function () {
  21044. return Scene._FOGMODE_EXP;
  21045. },
  21046. enumerable: true,
  21047. configurable: true
  21048. });
  21049. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21050. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21051. get: function () {
  21052. return Scene._FOGMODE_EXP2;
  21053. },
  21054. enumerable: true,
  21055. configurable: true
  21056. });
  21057. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21058. /** The fog density is following a linear function. */
  21059. get: function () {
  21060. return Scene._FOGMODE_LINEAR;
  21061. },
  21062. enumerable: true,
  21063. configurable: true
  21064. });
  21065. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21066. /**
  21067. * Texture used in all pbr material as the reflection texture.
  21068. * As in the majority of the scene they are the same (exception for multi room and so on),
  21069. * this is easier to reference from here than from all the materials.
  21070. */
  21071. get: function () {
  21072. return this._environmentTexture;
  21073. },
  21074. /**
  21075. * Texture used in all pbr material as the reflection texture.
  21076. * As in the majority of the scene they are the same (exception for multi room and so on),
  21077. * this is easier to set here than in all the materials.
  21078. */
  21079. set: function (value) {
  21080. if (this._environmentTexture === value) {
  21081. return;
  21082. }
  21083. this._environmentTexture = value;
  21084. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21085. },
  21086. enumerable: true,
  21087. configurable: true
  21088. });
  21089. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21090. /**
  21091. * Default image processing configuration used either in the rendering
  21092. * Forward main pass or through the imageProcessingPostProcess if present.
  21093. * As in the majority of the scene they are the same (exception for multi camera),
  21094. * this is easier to reference from here than from all the materials and post process.
  21095. *
  21096. * No setter as we it is a shared configuration, you can set the values instead.
  21097. */
  21098. get: function () {
  21099. return this._imageProcessingConfiguration;
  21100. },
  21101. enumerable: true,
  21102. configurable: true
  21103. });
  21104. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21105. get: function () {
  21106. return this._forcePointsCloud;
  21107. },
  21108. set: function (value) {
  21109. if (this._forcePointsCloud === value) {
  21110. return;
  21111. }
  21112. this._forcePointsCloud = value;
  21113. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21114. },
  21115. enumerable: true,
  21116. configurable: true
  21117. });
  21118. Object.defineProperty(Scene.prototype, "onDispose", {
  21119. /** A function to be executed when this scene is disposed. */
  21120. set: function (callback) {
  21121. if (this._onDisposeObserver) {
  21122. this.onDisposeObservable.remove(this._onDisposeObserver);
  21123. }
  21124. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21125. },
  21126. enumerable: true,
  21127. configurable: true
  21128. });
  21129. Object.defineProperty(Scene.prototype, "beforeRender", {
  21130. /** A function to be executed before rendering this scene */
  21131. set: function (callback) {
  21132. if (this._onBeforeRenderObserver) {
  21133. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21134. }
  21135. if (callback) {
  21136. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21137. }
  21138. },
  21139. enumerable: true,
  21140. configurable: true
  21141. });
  21142. Object.defineProperty(Scene.prototype, "afterRender", {
  21143. /** A function to be executed after rendering this scene */
  21144. set: function (callback) {
  21145. if (this._onAfterRenderObserver) {
  21146. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21147. }
  21148. if (callback) {
  21149. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21150. }
  21151. },
  21152. enumerable: true,
  21153. configurable: true
  21154. });
  21155. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21156. set: function (callback) {
  21157. if (this._onBeforeCameraRenderObserver) {
  21158. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21159. }
  21160. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21161. },
  21162. enumerable: true,
  21163. configurable: true
  21164. });
  21165. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21166. set: function (callback) {
  21167. if (this._onAfterCameraRenderObserver) {
  21168. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21169. }
  21170. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21171. },
  21172. enumerable: true,
  21173. configurable: true
  21174. });
  21175. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21176. get: function () {
  21177. if (!this._gamepadManager) {
  21178. this._gamepadManager = new BABYLON.GamepadManager(this);
  21179. }
  21180. return this._gamepadManager;
  21181. },
  21182. enumerable: true,
  21183. configurable: true
  21184. });
  21185. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21186. get: function () {
  21187. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21188. },
  21189. enumerable: true,
  21190. configurable: true
  21191. });
  21192. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21193. get: function () {
  21194. return this._useRightHandedSystem;
  21195. },
  21196. set: function (value) {
  21197. if (this._useRightHandedSystem === value) {
  21198. return;
  21199. }
  21200. this._useRightHandedSystem = value;
  21201. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21202. },
  21203. enumerable: true,
  21204. configurable: true
  21205. });
  21206. Scene.prototype.setStepId = function (newStepId) {
  21207. this._currentStepId = newStepId;
  21208. };
  21209. ;
  21210. Scene.prototype.getStepId = function () {
  21211. return this._currentStepId;
  21212. };
  21213. ;
  21214. Scene.prototype.getInternalStep = function () {
  21215. return this._currentInternalStep;
  21216. };
  21217. ;
  21218. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21219. get: function () {
  21220. return this._fogEnabled;
  21221. },
  21222. /**
  21223. * is fog enabled on this scene.
  21224. */
  21225. set: function (value) {
  21226. if (this._fogEnabled === value) {
  21227. return;
  21228. }
  21229. this._fogEnabled = value;
  21230. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21231. },
  21232. enumerable: true,
  21233. configurable: true
  21234. });
  21235. Object.defineProperty(Scene.prototype, "fogMode", {
  21236. get: function () {
  21237. return this._fogMode;
  21238. },
  21239. set: function (value) {
  21240. if (this._fogMode === value) {
  21241. return;
  21242. }
  21243. this._fogMode = value;
  21244. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21245. },
  21246. enumerable: true,
  21247. configurable: true
  21248. });
  21249. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21250. get: function () {
  21251. return this._shadowsEnabled;
  21252. },
  21253. set: function (value) {
  21254. if (this._shadowsEnabled === value) {
  21255. return;
  21256. }
  21257. this._shadowsEnabled = value;
  21258. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21259. },
  21260. enumerable: true,
  21261. configurable: true
  21262. });
  21263. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21264. get: function () {
  21265. return this._lightsEnabled;
  21266. },
  21267. set: function (value) {
  21268. if (this._lightsEnabled === value) {
  21269. return;
  21270. }
  21271. this._lightsEnabled = value;
  21272. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21273. },
  21274. enumerable: true,
  21275. configurable: true
  21276. });
  21277. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21278. /** The default material used on meshes when no material is affected */
  21279. get: function () {
  21280. if (!this._defaultMaterial) {
  21281. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21282. }
  21283. return this._defaultMaterial;
  21284. },
  21285. /** The default material used on meshes when no material is affected */
  21286. set: function (value) {
  21287. this._defaultMaterial = value;
  21288. },
  21289. enumerable: true,
  21290. configurable: true
  21291. });
  21292. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21293. get: function () {
  21294. return this._texturesEnabled;
  21295. },
  21296. set: function (value) {
  21297. if (this._texturesEnabled === value) {
  21298. return;
  21299. }
  21300. this._texturesEnabled = value;
  21301. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21302. },
  21303. enumerable: true,
  21304. configurable: true
  21305. });
  21306. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21307. get: function () {
  21308. return this._skeletonsEnabled;
  21309. },
  21310. set: function (value) {
  21311. if (this._skeletonsEnabled === value) {
  21312. return;
  21313. }
  21314. this._skeletonsEnabled = value;
  21315. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21316. },
  21317. enumerable: true,
  21318. configurable: true
  21319. });
  21320. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21321. get: function () {
  21322. if (!this._postProcessRenderPipelineManager) {
  21323. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21324. }
  21325. return this._postProcessRenderPipelineManager;
  21326. },
  21327. enumerable: true,
  21328. configurable: true
  21329. });
  21330. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21331. get: function () {
  21332. if (!this._mainSoundTrack) {
  21333. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21334. }
  21335. return this._mainSoundTrack;
  21336. },
  21337. enumerable: true,
  21338. configurable: true
  21339. });
  21340. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21341. get: function () {
  21342. return this._alternateRendering;
  21343. },
  21344. enumerable: true,
  21345. configurable: true
  21346. });
  21347. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21348. get: function () {
  21349. return this._frustumPlanes;
  21350. },
  21351. enumerable: true,
  21352. configurable: true
  21353. });
  21354. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21355. /**
  21356. * Gets the current geometry buffer associated to the scene.
  21357. */
  21358. get: function () {
  21359. return this._geometryBufferRenderer;
  21360. },
  21361. /**
  21362. * Sets the current geometry buffer for the scene.
  21363. */
  21364. set: function (geometryBufferRenderer) {
  21365. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21366. this._geometryBufferRenderer = geometryBufferRenderer;
  21367. }
  21368. },
  21369. enumerable: true,
  21370. configurable: true
  21371. });
  21372. Object.defineProperty(Scene.prototype, "debugLayer", {
  21373. // Properties
  21374. get: function () {
  21375. if (!this._debugLayer) {
  21376. this._debugLayer = new BABYLON.DebugLayer(this);
  21377. }
  21378. return this._debugLayer;
  21379. },
  21380. enumerable: true,
  21381. configurable: true
  21382. });
  21383. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21384. get: function () {
  21385. return this._workerCollisions;
  21386. },
  21387. set: function (enabled) {
  21388. if (!BABYLON.CollisionCoordinatorLegacy) {
  21389. return;
  21390. }
  21391. enabled = (enabled && !!Worker);
  21392. this._workerCollisions = enabled;
  21393. if (this.collisionCoordinator) {
  21394. this.collisionCoordinator.destroy();
  21395. }
  21396. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21397. this.collisionCoordinator.init(this);
  21398. },
  21399. enumerable: true,
  21400. configurable: true
  21401. });
  21402. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21403. get: function () {
  21404. return this._selectionOctree;
  21405. },
  21406. enumerable: true,
  21407. configurable: true
  21408. });
  21409. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21410. /**
  21411. * The mesh that is currently under the pointer.
  21412. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21413. */
  21414. get: function () {
  21415. return this._pointerOverMesh;
  21416. },
  21417. enumerable: true,
  21418. configurable: true
  21419. });
  21420. Object.defineProperty(Scene.prototype, "pointerX", {
  21421. /**
  21422. * Current on-screen X position of the pointer
  21423. * @return {number} X position of the pointer
  21424. */
  21425. get: function () {
  21426. return this._pointerX;
  21427. },
  21428. enumerable: true,
  21429. configurable: true
  21430. });
  21431. Object.defineProperty(Scene.prototype, "pointerY", {
  21432. /**
  21433. * Current on-screen Y position of the pointer
  21434. * @return {number} Y position of the pointer
  21435. */
  21436. get: function () {
  21437. return this._pointerY;
  21438. },
  21439. enumerable: true,
  21440. configurable: true
  21441. });
  21442. Scene.prototype.getCachedMaterial = function () {
  21443. return this._cachedMaterial;
  21444. };
  21445. Scene.prototype.getCachedEffect = function () {
  21446. return this._cachedEffect;
  21447. };
  21448. Scene.prototype.getCachedVisibility = function () {
  21449. return this._cachedVisibility;
  21450. };
  21451. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21452. if (visibility === void 0) { visibility = 1; }
  21453. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21454. };
  21455. Scene.prototype.getBoundingBoxRenderer = function () {
  21456. if (!this._boundingBoxRenderer) {
  21457. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21458. }
  21459. return this._boundingBoxRenderer;
  21460. };
  21461. Scene.prototype.getOutlineRenderer = function () {
  21462. return this._outlineRenderer;
  21463. };
  21464. Scene.prototype.getEngine = function () {
  21465. return this._engine;
  21466. };
  21467. Scene.prototype.getTotalVertices = function () {
  21468. return this._totalVertices.current;
  21469. };
  21470. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21471. get: function () {
  21472. return this._totalVertices;
  21473. },
  21474. enumerable: true,
  21475. configurable: true
  21476. });
  21477. Scene.prototype.getActiveIndices = function () {
  21478. return this._activeIndices.current;
  21479. };
  21480. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21481. get: function () {
  21482. return this._activeIndices;
  21483. },
  21484. enumerable: true,
  21485. configurable: true
  21486. });
  21487. Scene.prototype.getActiveParticles = function () {
  21488. return this._activeParticles.current;
  21489. };
  21490. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21491. get: function () {
  21492. return this._activeParticles;
  21493. },
  21494. enumerable: true,
  21495. configurable: true
  21496. });
  21497. Scene.prototype.getActiveBones = function () {
  21498. return this._activeBones.current;
  21499. };
  21500. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21501. get: function () {
  21502. return this._activeBones;
  21503. },
  21504. enumerable: true,
  21505. configurable: true
  21506. });
  21507. // Stats
  21508. Scene.prototype.getInterFramePerfCounter = function () {
  21509. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21510. return 0;
  21511. };
  21512. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21513. get: function () {
  21514. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21515. return null;
  21516. },
  21517. enumerable: true,
  21518. configurable: true
  21519. });
  21520. Scene.prototype.getLastFrameDuration = function () {
  21521. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21522. return 0;
  21523. };
  21524. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21525. get: function () {
  21526. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21527. return null;
  21528. },
  21529. enumerable: true,
  21530. configurable: true
  21531. });
  21532. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21533. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21534. return 0;
  21535. };
  21536. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21537. get: function () {
  21538. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21539. return null;
  21540. },
  21541. enumerable: true,
  21542. configurable: true
  21543. });
  21544. Scene.prototype.getActiveMeshes = function () {
  21545. return this._activeMeshes;
  21546. };
  21547. Scene.prototype.getRenderTargetsDuration = function () {
  21548. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21549. return 0;
  21550. };
  21551. Scene.prototype.getRenderDuration = function () {
  21552. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21553. return 0;
  21554. };
  21555. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21556. get: function () {
  21557. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21558. return null;
  21559. },
  21560. enumerable: true,
  21561. configurable: true
  21562. });
  21563. Scene.prototype.getParticlesDuration = function () {
  21564. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21565. return 0;
  21566. };
  21567. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21568. get: function () {
  21569. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21570. return null;
  21571. },
  21572. enumerable: true,
  21573. configurable: true
  21574. });
  21575. Scene.prototype.getSpritesDuration = function () {
  21576. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21577. return 0;
  21578. };
  21579. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21580. get: function () {
  21581. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21582. return null;
  21583. },
  21584. enumerable: true,
  21585. configurable: true
  21586. });
  21587. Scene.prototype.getAnimationRatio = function () {
  21588. return this._animationRatio;
  21589. };
  21590. Scene.prototype.getRenderId = function () {
  21591. return this._renderId;
  21592. };
  21593. Scene.prototype.incrementRenderId = function () {
  21594. this._renderId++;
  21595. };
  21596. Scene.prototype._updatePointerPosition = function (evt) {
  21597. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21598. if (!canvasRect) {
  21599. return;
  21600. }
  21601. this._pointerX = evt.clientX - canvasRect.left;
  21602. this._pointerY = evt.clientY - canvasRect.top;
  21603. this._unTranslatedPointerX = this._pointerX;
  21604. this._unTranslatedPointerY = this._pointerY;
  21605. };
  21606. Scene.prototype._createUbo = function () {
  21607. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21608. this._sceneUbo.addUniform("viewProjection", 16);
  21609. this._sceneUbo.addUniform("view", 16);
  21610. };
  21611. Scene.prototype._createAlternateUbo = function () {
  21612. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21613. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21614. this._alternateSceneUbo.addUniform("view", 16);
  21615. };
  21616. // Pointers handling
  21617. /**
  21618. * Use this method to simulate a pointer move on a mesh
  21619. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21620. */
  21621. Scene.prototype.simulatePointerMove = function (pickResult) {
  21622. var evt = new PointerEvent("pointermove");
  21623. return this._processPointerMove(pickResult, evt);
  21624. };
  21625. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21626. var canvas = this._engine.getRenderingCanvas();
  21627. if (!canvas) {
  21628. return this;
  21629. }
  21630. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21631. this.setPointerOverSprite(null);
  21632. this.setPointerOverMesh(pickResult.pickedMesh);
  21633. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21634. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21635. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21636. }
  21637. else {
  21638. canvas.style.cursor = this.hoverCursor;
  21639. }
  21640. }
  21641. else {
  21642. canvas.style.cursor = this.defaultCursor;
  21643. }
  21644. }
  21645. else {
  21646. this.setPointerOverMesh(null);
  21647. // Sprites
  21648. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21649. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21650. this.setPointerOverSprite(pickResult.pickedSprite);
  21651. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21652. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21653. }
  21654. else {
  21655. canvas.style.cursor = this.hoverCursor;
  21656. }
  21657. }
  21658. else {
  21659. this.setPointerOverSprite(null);
  21660. // Restore pointer
  21661. canvas.style.cursor = this.defaultCursor;
  21662. }
  21663. }
  21664. if (pickResult) {
  21665. if (this.onPointerMove) {
  21666. this.onPointerMove(evt, pickResult);
  21667. }
  21668. if (this.onPointerObservable.hasObservers()) {
  21669. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21670. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21671. this.onPointerObservable.notifyObservers(pi, type);
  21672. }
  21673. }
  21674. return this;
  21675. };
  21676. /**
  21677. * Use this method to simulate a pointer down on a mesh
  21678. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21679. */
  21680. Scene.prototype.simulatePointerDown = function (pickResult) {
  21681. var evt = new PointerEvent("pointerdown");
  21682. return this._processPointerDown(pickResult, evt);
  21683. };
  21684. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21685. var _this = this;
  21686. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21687. this._pickedDownMesh = pickResult.pickedMesh;
  21688. var actionManager = pickResult.pickedMesh.actionManager;
  21689. if (actionManager) {
  21690. if (actionManager.hasPickTriggers) {
  21691. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21692. switch (evt.button) {
  21693. case 0:
  21694. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21695. break;
  21696. case 1:
  21697. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21698. break;
  21699. case 2:
  21700. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21701. break;
  21702. }
  21703. }
  21704. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21705. window.setTimeout(function () {
  21706. 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);
  21707. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21708. if (_this._totalPointersPressed !== 0 &&
  21709. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21710. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21711. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21712. _this._startingPointerTime = 0;
  21713. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21714. }
  21715. }
  21716. }, Scene.LongPressDelay);
  21717. }
  21718. }
  21719. }
  21720. if (pickResult) {
  21721. if (this.onPointerDown) {
  21722. this.onPointerDown(evt, pickResult);
  21723. }
  21724. if (this.onPointerObservable.hasObservers()) {
  21725. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21726. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21727. this.onPointerObservable.notifyObservers(pi, type);
  21728. }
  21729. }
  21730. return this;
  21731. };
  21732. /**
  21733. * Use this method to simulate a pointer up on a mesh
  21734. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21735. */
  21736. Scene.prototype.simulatePointerUp = function (pickResult) {
  21737. var evt = new PointerEvent("pointerup");
  21738. var clickInfo = new ClickInfo();
  21739. clickInfo.singleClick = true;
  21740. clickInfo.ignore = true;
  21741. return this._processPointerUp(pickResult, evt, clickInfo);
  21742. };
  21743. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21744. if (pickResult && pickResult && pickResult.pickedMesh) {
  21745. this._pickedUpMesh = pickResult.pickedMesh;
  21746. if (this._pickedDownMesh === this._pickedUpMesh) {
  21747. if (this.onPointerPick) {
  21748. this.onPointerPick(evt, pickResult);
  21749. }
  21750. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21751. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21752. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21753. this.onPointerObservable.notifyObservers(pi, type);
  21754. }
  21755. }
  21756. if (pickResult.pickedMesh.actionManager) {
  21757. if (clickInfo.ignore) {
  21758. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21759. }
  21760. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21761. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21762. }
  21763. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21764. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21765. }
  21766. }
  21767. }
  21768. if (this._pickedDownMesh &&
  21769. this._pickedDownMesh.actionManager &&
  21770. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21771. this._pickedDownMesh !== this._pickedUpMesh) {
  21772. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21773. }
  21774. if (this.onPointerUp) {
  21775. this.onPointerUp(evt, pickResult);
  21776. }
  21777. if (this.onPointerObservable.hasObservers()) {
  21778. if (!clickInfo.ignore) {
  21779. if (!clickInfo.hasSwiped) {
  21780. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21781. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21782. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21783. this.onPointerObservable.notifyObservers(pi, type);
  21784. }
  21785. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21786. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21787. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21788. this.onPointerObservable.notifyObservers(pi, type);
  21789. }
  21790. }
  21791. }
  21792. else {
  21793. var type = BABYLON.PointerEventTypes.POINTERUP;
  21794. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21795. this.onPointerObservable.notifyObservers(pi, type);
  21796. }
  21797. }
  21798. return this;
  21799. };
  21800. /**
  21801. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21802. * @param attachUp defines if you want to attach events to pointerup
  21803. * @param attachDown defines if you want to attach events to pointerdown
  21804. * @param attachMove defines if you want to attach events to pointermove
  21805. */
  21806. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21807. var _this = this;
  21808. if (attachUp === void 0) { attachUp = true; }
  21809. if (attachDown === void 0) { attachDown = true; }
  21810. if (attachMove === void 0) { attachMove = true; }
  21811. this._initActionManager = function (act, clickInfo) {
  21812. if (!_this._meshPickProceed) {
  21813. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21814. _this._currentPickResult = pickResult;
  21815. if (pickResult) {
  21816. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21817. }
  21818. _this._meshPickProceed = true;
  21819. }
  21820. return act;
  21821. };
  21822. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21823. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21824. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21825. btn !== _this._previousButtonPressed) {
  21826. _this._doubleClickOccured = false;
  21827. clickInfo.singleClick = true;
  21828. clickInfo.ignore = false;
  21829. cb(clickInfo, _this._currentPickResult);
  21830. }
  21831. };
  21832. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21833. var clickInfo = new ClickInfo();
  21834. _this._currentPickResult = null;
  21835. var act = null;
  21836. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21837. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21838. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21839. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21840. act = _this._initActionManager(act, clickInfo);
  21841. if (act)
  21842. checkPicking = act.hasPickTriggers;
  21843. }
  21844. if (checkPicking) {
  21845. var btn = evt.button;
  21846. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21847. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21848. if (!clickInfo.hasSwiped) {
  21849. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21850. if (!checkSingleClickImmediately) {
  21851. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21852. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21853. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21854. act = _this._initActionManager(act, clickInfo);
  21855. if (act)
  21856. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21857. }
  21858. }
  21859. if (checkSingleClickImmediately) {
  21860. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21861. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21862. btn !== _this._previousButtonPressed) {
  21863. clickInfo.singleClick = true;
  21864. cb(clickInfo, _this._currentPickResult);
  21865. }
  21866. }
  21867. else {
  21868. // wait that no double click has been raised during the double click delay
  21869. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21870. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21871. }
  21872. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21873. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21874. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21875. act = _this._initActionManager(act, clickInfo);
  21876. if (act)
  21877. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21878. }
  21879. if (checkDoubleClick) {
  21880. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21881. if (btn === _this._previousButtonPressed &&
  21882. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21883. !_this._doubleClickOccured) {
  21884. // pointer has not moved for 2 clicks, it's a double click
  21885. if (!clickInfo.hasSwiped &&
  21886. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21887. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21888. _this._previousStartingPointerTime = 0;
  21889. _this._doubleClickOccured = true;
  21890. clickInfo.doubleClick = true;
  21891. clickInfo.ignore = false;
  21892. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21893. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21894. }
  21895. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21896. cb(clickInfo, _this._currentPickResult);
  21897. }
  21898. else {
  21899. _this._doubleClickOccured = false;
  21900. _this._previousStartingPointerTime = _this._startingPointerTime;
  21901. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21902. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21903. _this._previousButtonPressed = btn;
  21904. if (Scene.ExclusiveDoubleClickMode) {
  21905. if (_this._previousDelayedSimpleClickTimeout) {
  21906. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21907. }
  21908. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21909. cb(clickInfo, _this._previousPickResult);
  21910. }
  21911. else {
  21912. cb(clickInfo, _this._currentPickResult);
  21913. }
  21914. }
  21915. }
  21916. else {
  21917. _this._doubleClickOccured = false;
  21918. _this._previousStartingPointerTime = _this._startingPointerTime;
  21919. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21920. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21921. _this._previousButtonPressed = btn;
  21922. }
  21923. }
  21924. }
  21925. }
  21926. clickInfo.ignore = true;
  21927. cb(clickInfo, _this._currentPickResult);
  21928. };
  21929. this._spritePredicate = function (sprite) {
  21930. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  21931. };
  21932. this._onPointerMove = function (evt) {
  21933. _this._updatePointerPosition(evt);
  21934. // PreObservable support
  21935. if (_this.onPrePointerObservable.hasObservers()) {
  21936. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21937. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21938. _this.onPrePointerObservable.notifyObservers(pi, type);
  21939. if (pi.skipOnPointerObservable) {
  21940. return;
  21941. }
  21942. }
  21943. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21944. return;
  21945. }
  21946. if (!_this.pointerMovePredicate) {
  21947. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  21948. }
  21949. // Meshes
  21950. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  21951. _this._processPointerMove(pickResult, evt);
  21952. };
  21953. this._onPointerDown = function (evt) {
  21954. _this._totalPointersPressed++;
  21955. _this._pickedDownMesh = null;
  21956. _this._meshPickProceed = false;
  21957. _this._updatePointerPosition(evt);
  21958. if (_this.preventDefaultOnPointerDown && canvas) {
  21959. evt.preventDefault();
  21960. canvas.focus();
  21961. }
  21962. // PreObservable support
  21963. if (_this.onPrePointerObservable.hasObservers()) {
  21964. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21965. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21966. _this.onPrePointerObservable.notifyObservers(pi, type);
  21967. if (pi.skipOnPointerObservable) {
  21968. return;
  21969. }
  21970. }
  21971. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21972. return;
  21973. }
  21974. _this._startingPointerPosition.x = _this._pointerX;
  21975. _this._startingPointerPosition.y = _this._pointerY;
  21976. _this._startingPointerTime = new Date().getTime();
  21977. if (!_this.pointerDownPredicate) {
  21978. _this.pointerDownPredicate = function (mesh) {
  21979. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21980. };
  21981. }
  21982. // Meshes
  21983. _this._pickedDownMesh = null;
  21984. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21985. _this._processPointerDown(pickResult, evt);
  21986. // Sprites
  21987. _this._pickedDownSprite = null;
  21988. if (_this.spriteManagers.length > 0) {
  21989. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21990. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21991. if (pickResult.pickedSprite.actionManager) {
  21992. _this._pickedDownSprite = pickResult.pickedSprite;
  21993. switch (evt.button) {
  21994. case 0:
  21995. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21996. break;
  21997. case 1:
  21998. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21999. break;
  22000. case 2:
  22001. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22002. break;
  22003. }
  22004. if (pickResult.pickedSprite.actionManager) {
  22005. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22006. }
  22007. }
  22008. }
  22009. }
  22010. };
  22011. this._onPointerUp = function (evt) {
  22012. if (_this._totalPointersPressed === 0) {
  22013. return; // So we need to test it the pointer down was pressed before.
  22014. }
  22015. _this._totalPointersPressed--;
  22016. _this._pickedUpMesh = null;
  22017. _this._meshPickProceed = false;
  22018. _this._updatePointerPosition(evt);
  22019. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22020. // PreObservable support
  22021. if (_this.onPrePointerObservable.hasObservers()) {
  22022. if (!clickInfo.ignore) {
  22023. if (!clickInfo.hasSwiped) {
  22024. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22025. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22026. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22027. _this.onPrePointerObservable.notifyObservers(pi, type);
  22028. if (pi.skipOnPointerObservable) {
  22029. return;
  22030. }
  22031. }
  22032. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22033. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22034. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22035. _this.onPrePointerObservable.notifyObservers(pi, type);
  22036. if (pi.skipOnPointerObservable) {
  22037. return;
  22038. }
  22039. }
  22040. }
  22041. }
  22042. else {
  22043. var type = BABYLON.PointerEventTypes.POINTERUP;
  22044. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22045. _this.onPrePointerObservable.notifyObservers(pi, type);
  22046. if (pi.skipOnPointerObservable) {
  22047. return;
  22048. }
  22049. }
  22050. }
  22051. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22052. return;
  22053. }
  22054. if (!_this.pointerUpPredicate) {
  22055. _this.pointerUpPredicate = function (mesh) {
  22056. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22057. };
  22058. }
  22059. // Meshes
  22060. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22061. _this._initActionManager(null, clickInfo);
  22062. }
  22063. if (!pickResult) {
  22064. pickResult = _this._currentPickResult;
  22065. }
  22066. _this._processPointerUp(pickResult, evt, clickInfo);
  22067. // Sprites
  22068. if (_this.spriteManagers.length > 0) {
  22069. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22070. if (spritePickResult) {
  22071. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22072. if (spritePickResult.pickedSprite.actionManager) {
  22073. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22074. if (spritePickResult.pickedSprite.actionManager) {
  22075. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22076. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22077. }
  22078. }
  22079. }
  22080. }
  22081. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22082. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22083. }
  22084. }
  22085. }
  22086. _this._previousPickResult = _this._currentPickResult;
  22087. });
  22088. };
  22089. this._onKeyDown = function (evt) {
  22090. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22091. if (_this.onPreKeyboardObservable.hasObservers()) {
  22092. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22093. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22094. if (pi.skipOnPointerObservable) {
  22095. return;
  22096. }
  22097. }
  22098. if (_this.onKeyboardObservable.hasObservers()) {
  22099. var pi = new BABYLON.KeyboardInfo(type, evt);
  22100. _this.onKeyboardObservable.notifyObservers(pi, type);
  22101. }
  22102. if (_this.actionManager) {
  22103. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22104. }
  22105. };
  22106. this._onKeyUp = function (evt) {
  22107. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22108. if (_this.onPreKeyboardObservable.hasObservers()) {
  22109. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22110. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22111. if (pi.skipOnPointerObservable) {
  22112. return;
  22113. }
  22114. }
  22115. if (_this.onKeyboardObservable.hasObservers()) {
  22116. var pi = new BABYLON.KeyboardInfo(type, evt);
  22117. _this.onKeyboardObservable.notifyObservers(pi, type);
  22118. }
  22119. if (_this.actionManager) {
  22120. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22121. }
  22122. };
  22123. var engine = this.getEngine();
  22124. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22125. if (!canvas) {
  22126. return;
  22127. }
  22128. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22129. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22130. });
  22131. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22132. if (!canvas) {
  22133. return;
  22134. }
  22135. canvas.removeEventListener("keydown", _this._onKeyDown);
  22136. canvas.removeEventListener("keyup", _this._onKeyUp);
  22137. });
  22138. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22139. var canvas = this._engine.getRenderingCanvas();
  22140. if (!canvas) {
  22141. return;
  22142. }
  22143. if (attachMove) {
  22144. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22145. // Wheel
  22146. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22147. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22148. }
  22149. if (attachDown) {
  22150. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22151. }
  22152. if (attachUp) {
  22153. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22154. }
  22155. canvas.tabIndex = 1;
  22156. };
  22157. Scene.prototype.detachControl = function () {
  22158. var engine = this.getEngine();
  22159. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22160. var canvas = engine.getRenderingCanvas();
  22161. if (!canvas) {
  22162. return;
  22163. }
  22164. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22165. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22166. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22167. if (this._onCanvasBlurObserver) {
  22168. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22169. }
  22170. if (this._onCanvasFocusObserver) {
  22171. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22172. }
  22173. // Wheel
  22174. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22175. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22176. // Keyboard
  22177. canvas.removeEventListener("keydown", this._onKeyDown);
  22178. canvas.removeEventListener("keyup", this._onKeyUp);
  22179. // Observables
  22180. this.onKeyboardObservable.clear();
  22181. this.onPreKeyboardObservable.clear();
  22182. this.onPointerObservable.clear();
  22183. this.onPrePointerObservable.clear();
  22184. };
  22185. /**
  22186. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22187. * Delay loaded resources are not taking in account
  22188. * @return true if all required resources are ready
  22189. */
  22190. Scene.prototype.isReady = function () {
  22191. if (this._isDisposed) {
  22192. return false;
  22193. }
  22194. if (this._pendingData.length > 0) {
  22195. return false;
  22196. }
  22197. var index;
  22198. var engine = this.getEngine();
  22199. // Geometries
  22200. for (index = 0; index < this._geometries.length; index++) {
  22201. var geometry = this._geometries[index];
  22202. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22203. return false;
  22204. }
  22205. }
  22206. // Meshes
  22207. for (index = 0; index < this.meshes.length; index++) {
  22208. var mesh = this.meshes[index];
  22209. if (!mesh.isEnabled()) {
  22210. continue;
  22211. }
  22212. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22213. continue;
  22214. }
  22215. if (!mesh.isReady()) {
  22216. return false;
  22217. }
  22218. // Effect layers
  22219. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22220. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22221. var layer = _a[_i];
  22222. if (!layer.hasMesh(mesh)) {
  22223. continue;
  22224. }
  22225. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22226. var subMesh = _c[_b];
  22227. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22228. return false;
  22229. }
  22230. }
  22231. }
  22232. }
  22233. return true;
  22234. };
  22235. Scene.prototype.resetCachedMaterial = function () {
  22236. this._cachedMaterial = null;
  22237. this._cachedEffect = null;
  22238. this._cachedVisibility = null;
  22239. };
  22240. Scene.prototype.registerBeforeRender = function (func) {
  22241. this.onBeforeRenderObservable.add(func);
  22242. };
  22243. Scene.prototype.unregisterBeforeRender = function (func) {
  22244. this.onBeforeRenderObservable.removeCallback(func);
  22245. };
  22246. Scene.prototype.registerAfterRender = function (func) {
  22247. this.onAfterRenderObservable.add(func);
  22248. };
  22249. Scene.prototype.unregisterAfterRender = function (func) {
  22250. this.onAfterRenderObservable.removeCallback(func);
  22251. };
  22252. Scene.prototype._executeOnceBeforeRender = function (func) {
  22253. var _this = this;
  22254. var execFunc = function () {
  22255. func();
  22256. setTimeout(function () {
  22257. _this.unregisterBeforeRender(execFunc);
  22258. });
  22259. };
  22260. this.registerBeforeRender(execFunc);
  22261. };
  22262. /**
  22263. * The provided function will run before render once and will be disposed afterwards.
  22264. * A timeout delay can be provided so that the function will be executed in N ms.
  22265. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22266. * @param func The function to be executed.
  22267. * @param timeout optional delay in ms
  22268. */
  22269. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22270. var _this = this;
  22271. if (timeout !== undefined) {
  22272. setTimeout(function () {
  22273. _this._executeOnceBeforeRender(func);
  22274. }, timeout);
  22275. }
  22276. else {
  22277. this._executeOnceBeforeRender(func);
  22278. }
  22279. };
  22280. Scene.prototype._addPendingData = function (data) {
  22281. this._pendingData.push(data);
  22282. };
  22283. Scene.prototype._removePendingData = function (data) {
  22284. var wasLoading = this.isLoading;
  22285. var index = this._pendingData.indexOf(data);
  22286. if (index !== -1) {
  22287. this._pendingData.splice(index, 1);
  22288. }
  22289. if (wasLoading && !this.isLoading) {
  22290. this.onDataLoadedObservable.notifyObservers(this);
  22291. }
  22292. };
  22293. Scene.prototype.getWaitingItemsCount = function () {
  22294. return this._pendingData.length;
  22295. };
  22296. Object.defineProperty(Scene.prototype, "isLoading", {
  22297. get: function () {
  22298. return this._pendingData.length > 0;
  22299. },
  22300. enumerable: true,
  22301. configurable: true
  22302. });
  22303. /**
  22304. * Registers a function to be executed when the scene is ready.
  22305. * @param {Function} func - the function to be executed.
  22306. */
  22307. Scene.prototype.executeWhenReady = function (func) {
  22308. var _this = this;
  22309. this.onReadyObservable.add(func);
  22310. if (this._executeWhenReadyTimeoutId !== -1) {
  22311. return;
  22312. }
  22313. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22314. _this._checkIsReady();
  22315. }, 150);
  22316. };
  22317. /**
  22318. * Returns a promise that resolves when the scene is ready.
  22319. * @returns A promise that resolves when the scene is ready.
  22320. */
  22321. Scene.prototype.whenReadyAsync = function () {
  22322. var _this = this;
  22323. return new Promise(function (resolve) {
  22324. _this.executeWhenReady(function () {
  22325. resolve();
  22326. });
  22327. });
  22328. };
  22329. Scene.prototype._checkIsReady = function () {
  22330. var _this = this;
  22331. if (this.isReady()) {
  22332. this.onReadyObservable.notifyObservers(this);
  22333. this.onReadyObservable.clear();
  22334. this._executeWhenReadyTimeoutId = -1;
  22335. return;
  22336. }
  22337. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22338. _this._checkIsReady();
  22339. }, 150);
  22340. };
  22341. // Animations
  22342. /**
  22343. * Will start the animation sequence of a given target
  22344. * @param target - the target
  22345. * @param {number} from - from which frame should animation start
  22346. * @param {number} to - till which frame should animation run.
  22347. * @param {boolean} [loop] - should the animation loop
  22348. * @param {number} [speedRatio] - the speed in which to run the animation
  22349. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22350. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22351. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22352. * See BABYLON.Animatable
  22353. */
  22354. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22355. if (speedRatio === void 0) { speedRatio = 1.0; }
  22356. if (from > to && speedRatio > 0) {
  22357. speedRatio *= -1;
  22358. }
  22359. this.stopAnimation(target);
  22360. if (!animatable) {
  22361. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22362. }
  22363. // Local animations
  22364. if (target.animations) {
  22365. animatable.appendAnimations(target, target.animations);
  22366. }
  22367. // Children animations
  22368. if (target.getAnimatables) {
  22369. var animatables = target.getAnimatables();
  22370. for (var index = 0; index < animatables.length; index++) {
  22371. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22372. }
  22373. }
  22374. animatable.reset();
  22375. return animatable;
  22376. };
  22377. /**
  22378. * Begin a new animation on a given node
  22379. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22380. * @param {BABYLON.Animation[]} defines the list of animations to start
  22381. * @param {number} from defines the initial value
  22382. * @param {number} to defines the final value
  22383. * @param {boolean} loop defines if you want animation to loop (off by default)
  22384. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22385. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22386. * @returns the list of created animatables
  22387. */
  22388. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22389. if (speedRatio === undefined) {
  22390. speedRatio = 1.0;
  22391. }
  22392. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22393. return animatable;
  22394. };
  22395. /**
  22396. * Begin a new animation on a given node and its hierarchy
  22397. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22398. * @param {boolean} 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.
  22399. * @param {BABYLON.Animation[]} defines the list of animations to start
  22400. * @param {number} from defines the initial value
  22401. * @param {number} to defines the final value
  22402. * @param {boolean} loop defines if you want animation to loop (off by default)
  22403. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22404. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22405. * @returns the list of animatables created for all nodes
  22406. */
  22407. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22408. var children = target.getDescendants(directDescendantsOnly);
  22409. var result = [];
  22410. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22411. var child = children_1[_i];
  22412. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22413. }
  22414. return result;
  22415. };
  22416. Scene.prototype.getAnimatableByTarget = function (target) {
  22417. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22418. if (this._activeAnimatables[index].target === target) {
  22419. return this._activeAnimatables[index];
  22420. }
  22421. }
  22422. return null;
  22423. };
  22424. Object.defineProperty(Scene.prototype, "animatables", {
  22425. get: function () {
  22426. return this._activeAnimatables;
  22427. },
  22428. enumerable: true,
  22429. configurable: true
  22430. });
  22431. /**
  22432. * Will stop the animation of the given target
  22433. * @param target - the target
  22434. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22435. * @see beginAnimation
  22436. */
  22437. Scene.prototype.stopAnimation = function (target, animationName) {
  22438. var animatable = this.getAnimatableByTarget(target);
  22439. if (animatable) {
  22440. animatable.stop(animationName);
  22441. }
  22442. };
  22443. /**
  22444. * Stops and removes all animations that have been applied to the scene
  22445. */
  22446. Scene.prototype.stopAllAnimations = function () {
  22447. if (this._activeAnimatables) {
  22448. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22449. this._activeAnimatables[i].stop();
  22450. }
  22451. this._activeAnimatables = [];
  22452. }
  22453. };
  22454. Scene.prototype._animate = function () {
  22455. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22456. return;
  22457. }
  22458. // Getting time
  22459. var now = BABYLON.Tools.Now;
  22460. if (!this._animationTimeLast) {
  22461. if (this._pendingData.length > 0) {
  22462. return;
  22463. }
  22464. this._animationTimeLast = now;
  22465. }
  22466. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22467. this._animationTime += deltaTime;
  22468. this._animationTimeLast = now;
  22469. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22470. this._activeAnimatables[index]._animate(this._animationTime);
  22471. }
  22472. };
  22473. // Matrix
  22474. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22475. this._useAlternateCameraConfiguration = active;
  22476. };
  22477. Scene.prototype.getViewMatrix = function () {
  22478. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22479. };
  22480. Scene.prototype.getProjectionMatrix = function () {
  22481. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22482. };
  22483. Scene.prototype.getTransformMatrix = function () {
  22484. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22485. };
  22486. Scene.prototype.setTransformMatrix = function (view, projection) {
  22487. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22488. return;
  22489. }
  22490. this._viewUpdateFlag = view.updateFlag;
  22491. this._projectionUpdateFlag = projection.updateFlag;
  22492. this._viewMatrix = view;
  22493. this._projectionMatrix = projection;
  22494. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22495. // Update frustum
  22496. if (!this._frustumPlanes) {
  22497. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22498. }
  22499. else {
  22500. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22501. }
  22502. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22503. var otherCamera = this.activeCamera._alternateCamera;
  22504. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22505. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22506. }
  22507. if (this._sceneUbo.useUbo) {
  22508. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22509. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22510. this._sceneUbo.update();
  22511. }
  22512. };
  22513. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22514. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22515. return;
  22516. }
  22517. this._alternateViewUpdateFlag = view.updateFlag;
  22518. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22519. this._alternateViewMatrix = view;
  22520. this._alternateProjectionMatrix = projection;
  22521. if (!this._alternateTransformMatrix) {
  22522. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22523. }
  22524. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22525. if (!this._alternateSceneUbo) {
  22526. this._createAlternateUbo();
  22527. }
  22528. if (this._alternateSceneUbo.useUbo) {
  22529. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22530. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22531. this._alternateSceneUbo.update();
  22532. }
  22533. };
  22534. Scene.prototype.getSceneUniformBuffer = function () {
  22535. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22536. };
  22537. // Methods
  22538. Scene.prototype.getUniqueId = function () {
  22539. var result = Scene._uniqueIdCounter;
  22540. Scene._uniqueIdCounter++;
  22541. return result;
  22542. };
  22543. Scene.prototype.addMesh = function (newMesh) {
  22544. this.meshes.push(newMesh);
  22545. //notify the collision coordinator
  22546. if (this.collisionCoordinator) {
  22547. this.collisionCoordinator.onMeshAdded(newMesh);
  22548. }
  22549. newMesh._resyncLightSources();
  22550. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22551. };
  22552. Scene.prototype.removeMesh = function (toRemove) {
  22553. var index = this.meshes.indexOf(toRemove);
  22554. if (index !== -1) {
  22555. // Remove from the scene if mesh found
  22556. this.meshes.splice(index, 1);
  22557. }
  22558. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22559. return index;
  22560. };
  22561. Scene.prototype.addTransformNode = function (newTransformNode) {
  22562. this.transformNodes.push(newTransformNode);
  22563. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22564. };
  22565. Scene.prototype.removeTransformNode = function (toRemove) {
  22566. var index = this.transformNodes.indexOf(toRemove);
  22567. if (index !== -1) {
  22568. // Remove from the scene if found
  22569. this.transformNodes.splice(index, 1);
  22570. }
  22571. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22572. return index;
  22573. };
  22574. Scene.prototype.removeSkeleton = function (toRemove) {
  22575. var index = this.skeletons.indexOf(toRemove);
  22576. if (index !== -1) {
  22577. // Remove from the scene if found
  22578. this.skeletons.splice(index, 1);
  22579. }
  22580. return index;
  22581. };
  22582. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22583. var index = this.morphTargetManagers.indexOf(toRemove);
  22584. if (index !== -1) {
  22585. // Remove from the scene if found
  22586. this.morphTargetManagers.splice(index, 1);
  22587. }
  22588. return index;
  22589. };
  22590. Scene.prototype.removeLight = function (toRemove) {
  22591. var index = this.lights.indexOf(toRemove);
  22592. if (index !== -1) {
  22593. // Remove from meshes
  22594. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22595. var mesh = _a[_i];
  22596. mesh._removeLightSource(toRemove);
  22597. }
  22598. // Remove from the scene if mesh found
  22599. this.lights.splice(index, 1);
  22600. this.sortLightsByPriority();
  22601. }
  22602. this.onLightRemovedObservable.notifyObservers(toRemove);
  22603. return index;
  22604. };
  22605. Scene.prototype.removeCamera = function (toRemove) {
  22606. var index = this.cameras.indexOf(toRemove);
  22607. if (index !== -1) {
  22608. // Remove from the scene if mesh found
  22609. this.cameras.splice(index, 1);
  22610. }
  22611. // Remove from activeCameras
  22612. var index2 = this.activeCameras.indexOf(toRemove);
  22613. if (index2 !== -1) {
  22614. // Remove from the scene if mesh found
  22615. this.activeCameras.splice(index2, 1);
  22616. }
  22617. // Reset the activeCamera
  22618. if (this.activeCamera === toRemove) {
  22619. if (this.cameras.length > 0) {
  22620. this.activeCamera = this.cameras[0];
  22621. }
  22622. else {
  22623. this.activeCamera = null;
  22624. }
  22625. }
  22626. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22627. return index;
  22628. };
  22629. Scene.prototype.removeParticleSystem = function (toRemove) {
  22630. var index = this.particleSystems.indexOf(toRemove);
  22631. if (index !== -1) {
  22632. this.particleSystems.splice(index, 1);
  22633. }
  22634. return index;
  22635. };
  22636. ;
  22637. Scene.prototype.removeAnimation = function (toRemove) {
  22638. var index = this.animations.indexOf(toRemove);
  22639. if (index !== -1) {
  22640. this.animations.splice(index, 1);
  22641. }
  22642. return index;
  22643. };
  22644. ;
  22645. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22646. var index = this.multiMaterials.indexOf(toRemove);
  22647. if (index !== -1) {
  22648. this.multiMaterials.splice(index, 1);
  22649. }
  22650. return index;
  22651. };
  22652. ;
  22653. Scene.prototype.removeMaterial = function (toRemove) {
  22654. var index = this.materials.indexOf(toRemove);
  22655. if (index !== -1) {
  22656. this.materials.splice(index, 1);
  22657. }
  22658. return index;
  22659. };
  22660. ;
  22661. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22662. var index = this.lensFlareSystems.indexOf(toRemove);
  22663. if (index !== -1) {
  22664. this.lensFlareSystems.splice(index, 1);
  22665. }
  22666. return index;
  22667. };
  22668. ;
  22669. Scene.prototype.removeActionManager = function (toRemove) {
  22670. var index = this._actionManagers.indexOf(toRemove);
  22671. if (index !== -1) {
  22672. this._actionManagers.splice(index, 1);
  22673. }
  22674. return index;
  22675. };
  22676. ;
  22677. Scene.prototype.addLight = function (newLight) {
  22678. this.lights.push(newLight);
  22679. this.sortLightsByPriority();
  22680. // Add light to all meshes (To support if the light is removed and then readded)
  22681. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22682. var mesh = _a[_i];
  22683. if (mesh._lightSources.indexOf(newLight) === -1) {
  22684. mesh._lightSources.push(newLight);
  22685. mesh._resyncLightSources();
  22686. }
  22687. }
  22688. this.onNewLightAddedObservable.notifyObservers(newLight);
  22689. };
  22690. Scene.prototype.sortLightsByPriority = function () {
  22691. if (this.requireLightSorting) {
  22692. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22693. }
  22694. };
  22695. Scene.prototype.addCamera = function (newCamera) {
  22696. this.cameras.push(newCamera);
  22697. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22698. };
  22699. Scene.prototype.addSkeleton = function (newSkeleton) {
  22700. this.skeletons.push(newSkeleton);
  22701. };
  22702. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22703. this.particleSystems.push(newParticleSystem);
  22704. };
  22705. Scene.prototype.addAnimation = function (newAnimation) {
  22706. this.animations.push(newAnimation);
  22707. };
  22708. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22709. this.multiMaterials.push(newMultiMaterial);
  22710. };
  22711. Scene.prototype.addMaterial = function (newMaterial) {
  22712. this.materials.push(newMaterial);
  22713. };
  22714. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22715. this.morphTargetManagers.push(newMorphTargetManager);
  22716. };
  22717. Scene.prototype.addGeometry = function (newGeometrie) {
  22718. this._geometries.push(newGeometrie);
  22719. };
  22720. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22721. this.lensFlareSystems.push(newLensFlareSystem);
  22722. };
  22723. Scene.prototype.addActionManager = function (newActionManager) {
  22724. this._actionManagers.push(newActionManager);
  22725. };
  22726. /**
  22727. * Switch active camera
  22728. * @param {Camera} newCamera - new active camera
  22729. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22730. */
  22731. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22732. if (attachControl === void 0) { attachControl = true; }
  22733. var canvas = this._engine.getRenderingCanvas();
  22734. if (!canvas) {
  22735. return;
  22736. }
  22737. if (this.activeCamera) {
  22738. this.activeCamera.detachControl(canvas);
  22739. }
  22740. this.activeCamera = newCamera;
  22741. if (attachControl) {
  22742. newCamera.attachControl(canvas);
  22743. }
  22744. };
  22745. /**
  22746. * sets the active camera of the scene using its ID
  22747. * @param {string} id - the camera's ID
  22748. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22749. * @see activeCamera
  22750. */
  22751. Scene.prototype.setActiveCameraByID = function (id) {
  22752. var camera = this.getCameraByID(id);
  22753. if (camera) {
  22754. this.activeCamera = camera;
  22755. return camera;
  22756. }
  22757. return null;
  22758. };
  22759. /**
  22760. * sets the active camera of the scene using its name
  22761. * @param {string} name - the camera's name
  22762. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22763. * @see activeCamera
  22764. */
  22765. Scene.prototype.setActiveCameraByName = function (name) {
  22766. var camera = this.getCameraByName(name);
  22767. if (camera) {
  22768. this.activeCamera = camera;
  22769. return camera;
  22770. }
  22771. return null;
  22772. };
  22773. /**
  22774. * get an animation group using its name
  22775. * @param {string} the material's name
  22776. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  22777. */
  22778. Scene.prototype.getAnimationGroupByName = function (name) {
  22779. for (var index = 0; index < this.animationGroups.length; index++) {
  22780. if (this.animationGroups[index].name === name) {
  22781. return this.animationGroups[index];
  22782. }
  22783. }
  22784. return null;
  22785. };
  22786. /**
  22787. * get a material using its id
  22788. * @param {string} the material's ID
  22789. * @return {BABYLON.Material|null} the material or null if none found.
  22790. */
  22791. Scene.prototype.getMaterialByID = function (id) {
  22792. for (var index = 0; index < this.materials.length; index++) {
  22793. if (this.materials[index].id === id) {
  22794. return this.materials[index];
  22795. }
  22796. }
  22797. return null;
  22798. };
  22799. /**
  22800. * get a material using its name
  22801. * @param {string} the material's name
  22802. * @return {BABYLON.Material|null} the material or null if none found.
  22803. */
  22804. Scene.prototype.getMaterialByName = function (name) {
  22805. for (var index = 0; index < this.materials.length; index++) {
  22806. if (this.materials[index].name === name) {
  22807. return this.materials[index];
  22808. }
  22809. }
  22810. return null;
  22811. };
  22812. Scene.prototype.getLensFlareSystemByName = function (name) {
  22813. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22814. if (this.lensFlareSystems[index].name === name) {
  22815. return this.lensFlareSystems[index];
  22816. }
  22817. }
  22818. return null;
  22819. };
  22820. Scene.prototype.getLensFlareSystemByID = function (id) {
  22821. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22822. if (this.lensFlareSystems[index].id === id) {
  22823. return this.lensFlareSystems[index];
  22824. }
  22825. }
  22826. return null;
  22827. };
  22828. Scene.prototype.getCameraByID = function (id) {
  22829. for (var index = 0; index < this.cameras.length; index++) {
  22830. if (this.cameras[index].id === id) {
  22831. return this.cameras[index];
  22832. }
  22833. }
  22834. return null;
  22835. };
  22836. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22837. for (var index = 0; index < this.cameras.length; index++) {
  22838. if (this.cameras[index].uniqueId === uniqueId) {
  22839. return this.cameras[index];
  22840. }
  22841. }
  22842. return null;
  22843. };
  22844. /**
  22845. * get a camera using its name
  22846. * @param {string} the camera's name
  22847. * @return {BABYLON.Camera|null} the camera or null if none found.
  22848. */
  22849. Scene.prototype.getCameraByName = function (name) {
  22850. for (var index = 0; index < this.cameras.length; index++) {
  22851. if (this.cameras[index].name === name) {
  22852. return this.cameras[index];
  22853. }
  22854. }
  22855. return null;
  22856. };
  22857. /**
  22858. * get a bone using its id
  22859. * @param {string} the bone's id
  22860. * @return {BABYLON.Bone|null} the bone or null if not found
  22861. */
  22862. Scene.prototype.getBoneByID = function (id) {
  22863. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22864. var skeleton = this.skeletons[skeletonIndex];
  22865. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22866. if (skeleton.bones[boneIndex].id === id) {
  22867. return skeleton.bones[boneIndex];
  22868. }
  22869. }
  22870. }
  22871. return null;
  22872. };
  22873. /**
  22874. * get a bone using its id
  22875. * @param {string} the bone's name
  22876. * @return {BABYLON.Bone|null} the bone or null if not found
  22877. */
  22878. Scene.prototype.getBoneByName = function (name) {
  22879. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22880. var skeleton = this.skeletons[skeletonIndex];
  22881. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22882. if (skeleton.bones[boneIndex].name === name) {
  22883. return skeleton.bones[boneIndex];
  22884. }
  22885. }
  22886. }
  22887. return null;
  22888. };
  22889. /**
  22890. * get a light node using its name
  22891. * @param {string} the light's name
  22892. * @return {BABYLON.Light|null} the light or null if none found.
  22893. */
  22894. Scene.prototype.getLightByName = function (name) {
  22895. for (var index = 0; index < this.lights.length; index++) {
  22896. if (this.lights[index].name === name) {
  22897. return this.lights[index];
  22898. }
  22899. }
  22900. return null;
  22901. };
  22902. /**
  22903. * get a light node using its ID
  22904. * @param {string} the light's id
  22905. * @return {BABYLON.Light|null} the light or null if none found.
  22906. */
  22907. Scene.prototype.getLightByID = function (id) {
  22908. for (var index = 0; index < this.lights.length; index++) {
  22909. if (this.lights[index].id === id) {
  22910. return this.lights[index];
  22911. }
  22912. }
  22913. return null;
  22914. };
  22915. /**
  22916. * get a light node using its scene-generated unique ID
  22917. * @param {number} the light's unique id
  22918. * @return {BABYLON.Light|null} the light or null if none found.
  22919. */
  22920. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  22921. for (var index = 0; index < this.lights.length; index++) {
  22922. if (this.lights[index].uniqueId === uniqueId) {
  22923. return this.lights[index];
  22924. }
  22925. }
  22926. return null;
  22927. };
  22928. /**
  22929. * get a particle system by id
  22930. * @param id {number} the particle system id
  22931. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  22932. */
  22933. Scene.prototype.getParticleSystemByID = function (id) {
  22934. for (var index = 0; index < this.particleSystems.length; index++) {
  22935. if (this.particleSystems[index].id === id) {
  22936. return this.particleSystems[index];
  22937. }
  22938. }
  22939. return null;
  22940. };
  22941. /**
  22942. * get a geometry using its ID
  22943. * @param {string} the geometry's id
  22944. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  22945. */
  22946. Scene.prototype.getGeometryByID = function (id) {
  22947. for (var index = 0; index < this._geometries.length; index++) {
  22948. if (this._geometries[index].id === id) {
  22949. return this._geometries[index];
  22950. }
  22951. }
  22952. return null;
  22953. };
  22954. /**
  22955. * add a new geometry to this scene.
  22956. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  22957. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  22958. * @return {boolean} was the geometry added or not
  22959. */
  22960. Scene.prototype.pushGeometry = function (geometry, force) {
  22961. if (!force && this.getGeometryByID(geometry.id)) {
  22962. return false;
  22963. }
  22964. this._geometries.push(geometry);
  22965. //notify the collision coordinator
  22966. if (this.collisionCoordinator) {
  22967. this.collisionCoordinator.onGeometryAdded(geometry);
  22968. }
  22969. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  22970. return true;
  22971. };
  22972. /**
  22973. * Removes an existing geometry
  22974. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  22975. * @return {boolean} was the geometry removed or not
  22976. */
  22977. Scene.prototype.removeGeometry = function (geometry) {
  22978. var index = this._geometries.indexOf(geometry);
  22979. if (index > -1) {
  22980. this._geometries.splice(index, 1);
  22981. //notify the collision coordinator
  22982. if (this.collisionCoordinator) {
  22983. this.collisionCoordinator.onGeometryDeleted(geometry);
  22984. }
  22985. this.onGeometryRemovedObservable.notifyObservers(geometry);
  22986. return true;
  22987. }
  22988. return false;
  22989. };
  22990. Scene.prototype.getGeometries = function () {
  22991. return this._geometries;
  22992. };
  22993. /**
  22994. * Get the first added mesh found of a given ID
  22995. * @param {string} id - the id to search for
  22996. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22997. */
  22998. Scene.prototype.getMeshByID = function (id) {
  22999. for (var index = 0; index < this.meshes.length; index++) {
  23000. if (this.meshes[index].id === id) {
  23001. return this.meshes[index];
  23002. }
  23003. }
  23004. return null;
  23005. };
  23006. Scene.prototype.getMeshesByID = function (id) {
  23007. return this.meshes.filter(function (m) {
  23008. return m.id === id;
  23009. });
  23010. };
  23011. /**
  23012. * Get the first added transform node found of a given ID
  23013. * @param {string} id - the id to search for
  23014. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23015. */
  23016. Scene.prototype.getTransformNodeByID = function (id) {
  23017. for (var index = 0; index < this.transformNodes.length; index++) {
  23018. if (this.transformNodes[index].id === id) {
  23019. return this.transformNodes[index];
  23020. }
  23021. }
  23022. return null;
  23023. };
  23024. Scene.prototype.getTransformNodesByID = function (id) {
  23025. return this.transformNodes.filter(function (m) {
  23026. return m.id === id;
  23027. });
  23028. };
  23029. /**
  23030. * Get a mesh with its auto-generated unique id
  23031. * @param {number} uniqueId - the unique id to search for
  23032. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23033. */
  23034. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23035. for (var index = 0; index < this.meshes.length; index++) {
  23036. if (this.meshes[index].uniqueId === uniqueId) {
  23037. return this.meshes[index];
  23038. }
  23039. }
  23040. return null;
  23041. };
  23042. /**
  23043. * Get a the last added mesh found of a given ID
  23044. * @param {string} id - the id to search for
  23045. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23046. */
  23047. Scene.prototype.getLastMeshByID = function (id) {
  23048. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23049. if (this.meshes[index].id === id) {
  23050. return this.meshes[index];
  23051. }
  23052. }
  23053. return null;
  23054. };
  23055. /**
  23056. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23057. * @param {string} id - the id to search for
  23058. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23059. */
  23060. Scene.prototype.getLastEntryByID = function (id) {
  23061. var index;
  23062. for (index = this.meshes.length - 1; index >= 0; index--) {
  23063. if (this.meshes[index].id === id) {
  23064. return this.meshes[index];
  23065. }
  23066. }
  23067. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23068. if (this.transformNodes[index].id === id) {
  23069. return this.transformNodes[index];
  23070. }
  23071. }
  23072. for (index = this.cameras.length - 1; index >= 0; index--) {
  23073. if (this.cameras[index].id === id) {
  23074. return this.cameras[index];
  23075. }
  23076. }
  23077. for (index = this.lights.length - 1; index >= 0; index--) {
  23078. if (this.lights[index].id === id) {
  23079. return this.lights[index];
  23080. }
  23081. }
  23082. return null;
  23083. };
  23084. Scene.prototype.getNodeByID = function (id) {
  23085. var mesh = this.getMeshByID(id);
  23086. if (mesh) {
  23087. return mesh;
  23088. }
  23089. var light = this.getLightByID(id);
  23090. if (light) {
  23091. return light;
  23092. }
  23093. var camera = this.getCameraByID(id);
  23094. if (camera) {
  23095. return camera;
  23096. }
  23097. var bone = this.getBoneByID(id);
  23098. return bone;
  23099. };
  23100. Scene.prototype.getNodeByName = function (name) {
  23101. var mesh = this.getMeshByName(name);
  23102. if (mesh) {
  23103. return mesh;
  23104. }
  23105. var light = this.getLightByName(name);
  23106. if (light) {
  23107. return light;
  23108. }
  23109. var camera = this.getCameraByName(name);
  23110. if (camera) {
  23111. return camera;
  23112. }
  23113. var bone = this.getBoneByName(name);
  23114. return bone;
  23115. };
  23116. Scene.prototype.getMeshByName = function (name) {
  23117. for (var index = 0; index < this.meshes.length; index++) {
  23118. if (this.meshes[index].name === name) {
  23119. return this.meshes[index];
  23120. }
  23121. }
  23122. return null;
  23123. };
  23124. Scene.prototype.getTransformNodeByName = function (name) {
  23125. for (var index = 0; index < this.transformNodes.length; index++) {
  23126. if (this.transformNodes[index].name === name) {
  23127. return this.transformNodes[index];
  23128. }
  23129. }
  23130. return null;
  23131. };
  23132. Scene.prototype.getSoundByName = function (name) {
  23133. var index;
  23134. if (BABYLON.AudioEngine) {
  23135. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23136. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23137. return this.mainSoundTrack.soundCollection[index];
  23138. }
  23139. }
  23140. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23141. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23142. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23143. return this.soundTracks[sdIndex].soundCollection[index];
  23144. }
  23145. }
  23146. }
  23147. }
  23148. return null;
  23149. };
  23150. Scene.prototype.getLastSkeletonByID = function (id) {
  23151. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23152. if (this.skeletons[index].id === id) {
  23153. return this.skeletons[index];
  23154. }
  23155. }
  23156. return null;
  23157. };
  23158. Scene.prototype.getSkeletonById = function (id) {
  23159. for (var index = 0; index < this.skeletons.length; index++) {
  23160. if (this.skeletons[index].id === id) {
  23161. return this.skeletons[index];
  23162. }
  23163. }
  23164. return null;
  23165. };
  23166. Scene.prototype.getSkeletonByName = function (name) {
  23167. for (var index = 0; index < this.skeletons.length; index++) {
  23168. if (this.skeletons[index].name === name) {
  23169. return this.skeletons[index];
  23170. }
  23171. }
  23172. return null;
  23173. };
  23174. Scene.prototype.getMorphTargetManagerById = function (id) {
  23175. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23176. if (this.morphTargetManagers[index].uniqueId === id) {
  23177. return this.morphTargetManagers[index];
  23178. }
  23179. }
  23180. return null;
  23181. };
  23182. Scene.prototype.isActiveMesh = function (mesh) {
  23183. return (this._activeMeshes.indexOf(mesh) !== -1);
  23184. };
  23185. /**
  23186. * Return a the first highlight layer of the scene with a given name.
  23187. * @param name The name of the highlight layer to look for.
  23188. * @return The highlight layer if found otherwise null.
  23189. */
  23190. Scene.prototype.getHighlightLayerByName = function (name) {
  23191. for (var index = 0; index < this.effectLayers.length; index++) {
  23192. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23193. return this.effectLayers[index];
  23194. }
  23195. }
  23196. return null;
  23197. };
  23198. /**
  23199. * Return a the first highlight layer of the scene with a given name.
  23200. * @param name The name of the highlight layer to look for.
  23201. * @return The highlight layer if found otherwise null.
  23202. */
  23203. Scene.prototype.getGlowLayerByName = function (name) {
  23204. for (var index = 0; index < this.effectLayers.length; index++) {
  23205. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23206. return this.effectLayers[index];
  23207. }
  23208. }
  23209. return null;
  23210. };
  23211. Object.defineProperty(Scene.prototype, "uid", {
  23212. /**
  23213. * Return a unique id as a string which can serve as an identifier for the scene
  23214. */
  23215. get: function () {
  23216. if (!this._uid) {
  23217. this._uid = BABYLON.Tools.RandomId();
  23218. }
  23219. return this._uid;
  23220. },
  23221. enumerable: true,
  23222. configurable: true
  23223. });
  23224. /**
  23225. * Add an externaly attached data from its key.
  23226. * This method call will fail and return false, if such key already exists.
  23227. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23228. * @param key the unique key that identifies the data
  23229. * @param data the data object to associate to the key for this Engine instance
  23230. * @return true if no such key were already present and the data was added successfully, false otherwise
  23231. */
  23232. Scene.prototype.addExternalData = function (key, data) {
  23233. if (!this._externalData) {
  23234. this._externalData = new BABYLON.StringDictionary();
  23235. }
  23236. return this._externalData.add(key, data);
  23237. };
  23238. /**
  23239. * Get an externaly attached data from its key
  23240. * @param key the unique key that identifies the data
  23241. * @return the associated data, if present (can be null), or undefined if not present
  23242. */
  23243. Scene.prototype.getExternalData = function (key) {
  23244. if (!this._externalData) {
  23245. return null;
  23246. }
  23247. return this._externalData.get(key);
  23248. };
  23249. /**
  23250. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23251. * @param key the unique key that identifies the data
  23252. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23253. * @return the associated data, can be null if the factory returned null.
  23254. */
  23255. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23256. if (!this._externalData) {
  23257. this._externalData = new BABYLON.StringDictionary();
  23258. }
  23259. return this._externalData.getOrAddWithFactory(key, factory);
  23260. };
  23261. /**
  23262. * Remove an externaly attached data from the Engine instance
  23263. * @param key the unique key that identifies the data
  23264. * @return true if the data was successfully removed, false if it doesn't exist
  23265. */
  23266. Scene.prototype.removeExternalData = function (key) {
  23267. return this._externalData.remove(key);
  23268. };
  23269. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23270. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23271. if (mesh.showSubMeshesBoundingBox) {
  23272. var boundingInfo = subMesh.getBoundingInfo();
  23273. if (boundingInfo !== null && boundingInfo !== undefined) {
  23274. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23275. }
  23276. }
  23277. var material = subMesh.getMaterial();
  23278. if (material !== null && material !== undefined) {
  23279. // Render targets
  23280. if (material.getRenderTargetTextures !== undefined) {
  23281. if (this._processedMaterials.indexOf(material) === -1) {
  23282. this._processedMaterials.push(material);
  23283. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23284. }
  23285. }
  23286. // Dispatch
  23287. this._activeIndices.addCount(subMesh.indexCount, false);
  23288. this._renderingManager.dispatch(subMesh, mesh, material);
  23289. }
  23290. }
  23291. };
  23292. Scene.prototype._isInIntermediateRendering = function () {
  23293. return this._intermediateRendering;
  23294. };
  23295. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23296. this._activeMeshCandidateProvider = provider;
  23297. };
  23298. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23299. return this._activeMeshCandidateProvider;
  23300. };
  23301. /**
  23302. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23303. */
  23304. Scene.prototype.freezeActiveMeshes = function () {
  23305. this._evaluateActiveMeshes();
  23306. this._activeMeshesFrozen = true;
  23307. return this;
  23308. };
  23309. /**
  23310. * Use this function to restart evaluating active meshes on every frame
  23311. */
  23312. Scene.prototype.unfreezeActiveMeshes = function () {
  23313. this._activeMeshesFrozen = false;
  23314. return this;
  23315. };
  23316. Scene.prototype._evaluateActiveMeshes = function () {
  23317. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23318. return;
  23319. }
  23320. if (!this.activeCamera) {
  23321. return;
  23322. }
  23323. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23324. this.activeCamera._activeMeshes.reset();
  23325. this._activeMeshes.reset();
  23326. this._renderingManager.reset();
  23327. this._processedMaterials.reset();
  23328. this._activeParticleSystems.reset();
  23329. this._activeSkeletons.reset();
  23330. this._softwareSkinnedMeshes.reset();
  23331. if (this._boundingBoxRenderer) {
  23332. this._boundingBoxRenderer.reset();
  23333. }
  23334. // Meshes
  23335. var meshes;
  23336. var len;
  23337. var checkIsEnabled = true;
  23338. // Determine mesh candidates
  23339. if (this._activeMeshCandidateProvider !== undefined) {
  23340. // Use _activeMeshCandidateProvider
  23341. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23342. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23343. if (meshes !== undefined) {
  23344. len = meshes.length;
  23345. }
  23346. else {
  23347. len = 0;
  23348. }
  23349. }
  23350. else if (this._selectionOctree !== undefined) {
  23351. // Octree
  23352. var selection = this._selectionOctree.select(this._frustumPlanes);
  23353. meshes = selection.data;
  23354. len = selection.length;
  23355. }
  23356. else {
  23357. // Full scene traversal
  23358. len = this.meshes.length;
  23359. meshes = this.meshes;
  23360. }
  23361. // Check each mesh
  23362. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23363. mesh = meshes[meshIndex];
  23364. if (mesh.isBlocked) {
  23365. continue;
  23366. }
  23367. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23368. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23369. continue;
  23370. }
  23371. mesh.computeWorldMatrix();
  23372. // Intersections
  23373. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23374. this._meshesForIntersections.pushNoDuplicate(mesh);
  23375. }
  23376. // Switch to current LOD
  23377. meshLOD = mesh.getLOD(this.activeCamera);
  23378. if (meshLOD === undefined || meshLOD === null) {
  23379. continue;
  23380. }
  23381. mesh._preActivate();
  23382. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23383. this._activeMeshes.push(mesh);
  23384. this.activeCamera._activeMeshes.push(mesh);
  23385. mesh._activate(this._renderId);
  23386. if (meshLOD !== mesh) {
  23387. meshLOD._activate(this._renderId);
  23388. }
  23389. this._activeMesh(mesh, meshLOD);
  23390. }
  23391. }
  23392. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23393. // Particle systems
  23394. if (this.particlesEnabled) {
  23395. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23396. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23397. var particleSystem = this.particleSystems[particleIndex];
  23398. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23399. continue;
  23400. }
  23401. var emitter = particleSystem.emitter;
  23402. if (!emitter.position || emitter.isEnabled()) {
  23403. this._activeParticleSystems.push(particleSystem);
  23404. particleSystem.animate();
  23405. this._renderingManager.dispatchParticles(particleSystem);
  23406. }
  23407. }
  23408. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23409. }
  23410. };
  23411. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23412. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23413. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23414. mesh.skeleton.prepare();
  23415. }
  23416. if (!mesh.computeBonesUsingShaders) {
  23417. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23418. }
  23419. }
  23420. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23421. var boundingInfo = sourceMesh.getBoundingInfo();
  23422. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23423. }
  23424. if (mesh !== undefined && mesh !== null
  23425. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23426. // Submeshes Octrees
  23427. var len;
  23428. var subMeshes;
  23429. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23430. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23431. len = intersections.length;
  23432. subMeshes = intersections.data;
  23433. }
  23434. else {
  23435. subMeshes = mesh.subMeshes;
  23436. len = subMeshes.length;
  23437. }
  23438. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23439. subMesh = subMeshes[subIndex];
  23440. this._evaluateSubMesh(subMesh, mesh);
  23441. }
  23442. }
  23443. };
  23444. Scene.prototype.updateTransformMatrix = function (force) {
  23445. if (!this.activeCamera) {
  23446. return;
  23447. }
  23448. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23449. };
  23450. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23451. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23452. };
  23453. Scene.prototype._renderForCamera = function (camera) {
  23454. if (camera && camera._skipRendering) {
  23455. return;
  23456. }
  23457. var engine = this._engine;
  23458. this.activeCamera = camera;
  23459. if (!this.activeCamera)
  23460. throw new Error("Active camera not set");
  23461. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23462. // Viewport
  23463. engine.setViewport(this.activeCamera.viewport);
  23464. // Camera
  23465. this.resetCachedMaterial();
  23466. this._renderId++;
  23467. this.activeCamera.update();
  23468. this.updateTransformMatrix();
  23469. if (camera._alternateCamera) {
  23470. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23471. this._alternateRendering = true;
  23472. }
  23473. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23474. // Meshes
  23475. this._evaluateActiveMeshes();
  23476. // Software skinning
  23477. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23478. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23479. mesh.applySkeleton(mesh.skeleton);
  23480. }
  23481. // Render targets
  23482. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23483. var needsRestoreFrameBuffer = false;
  23484. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23485. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23486. }
  23487. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23488. this._intermediateRendering = true;
  23489. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23490. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23491. var renderTarget = this._renderTargets.data[renderIndex];
  23492. if (renderTarget._shouldRender()) {
  23493. this._renderId++;
  23494. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23495. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23496. }
  23497. }
  23498. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23499. this._intermediateRendering = false;
  23500. this._renderId++;
  23501. needsRestoreFrameBuffer = true; // Restore back buffer
  23502. }
  23503. // Render EffecttLayer Texture
  23504. var stencilState = this._engine.getStencilBuffer();
  23505. var renderEffects = false;
  23506. var needStencil = false;
  23507. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  23508. this._intermediateRendering = true;
  23509. for (var i = 0; i < this.effectLayers.length; i++) {
  23510. var effectLayer = this.effectLayers[i];
  23511. if (effectLayer.shouldRender() &&
  23512. (!effectLayer.camera ||
  23513. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  23514. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23515. renderEffects = true;
  23516. needStencil = needStencil || effectLayer.needStencil();
  23517. var renderTarget = effectLayer._mainTexture;
  23518. if (renderTarget._shouldRender()) {
  23519. this._renderId++;
  23520. renderTarget.render(false, false);
  23521. needsRestoreFrameBuffer = true;
  23522. }
  23523. }
  23524. }
  23525. this._intermediateRendering = false;
  23526. this._renderId++;
  23527. }
  23528. if (needsRestoreFrameBuffer) {
  23529. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23530. }
  23531. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23532. // Prepare Frame
  23533. this.postProcessManager._prepareFrame();
  23534. // Backgrounds
  23535. var layerIndex;
  23536. var layer;
  23537. if (this.layers.length) {
  23538. engine.setDepthBuffer(false);
  23539. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23540. layer = this.layers[layerIndex];
  23541. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23542. layer.render();
  23543. }
  23544. }
  23545. engine.setDepthBuffer(true);
  23546. }
  23547. // Activate effect Layer stencil
  23548. if (needStencil) {
  23549. this._engine.setStencilBuffer(true);
  23550. }
  23551. // Render
  23552. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23553. this._renderingManager.render(null, null, true, true);
  23554. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23555. // Restore effect Layer stencil
  23556. if (needStencil) {
  23557. this._engine.setStencilBuffer(stencilState);
  23558. }
  23559. // Bounding boxes
  23560. if (this._boundingBoxRenderer) {
  23561. this._boundingBoxRenderer.render();
  23562. }
  23563. // Lens flares
  23564. if (this.lensFlaresEnabled) {
  23565. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23566. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23567. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23568. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23569. lensFlareSystem.render();
  23570. }
  23571. }
  23572. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23573. }
  23574. // Foregrounds
  23575. if (this.layers.length) {
  23576. engine.setDepthBuffer(false);
  23577. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23578. layer = this.layers[layerIndex];
  23579. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23580. layer.render();
  23581. }
  23582. }
  23583. engine.setDepthBuffer(true);
  23584. }
  23585. // Effect Layer
  23586. if (renderEffects) {
  23587. engine.setDepthBuffer(false);
  23588. for (var i = 0; i < this.effectLayers.length; i++) {
  23589. if (this.effectLayers[i].shouldRender()) {
  23590. this.effectLayers[i].render();
  23591. }
  23592. }
  23593. engine.setDepthBuffer(true);
  23594. }
  23595. // Finalize frame
  23596. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23597. // Reset some special arrays
  23598. this._renderTargets.reset();
  23599. this._alternateRendering = false;
  23600. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23601. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23602. };
  23603. Scene.prototype._processSubCameras = function (camera) {
  23604. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23605. this._renderForCamera(camera);
  23606. return;
  23607. }
  23608. // Update camera
  23609. if (this.activeCamera) {
  23610. this.activeCamera.update();
  23611. }
  23612. // rig cameras
  23613. for (var index = 0; index < camera._rigCameras.length; index++) {
  23614. this._renderForCamera(camera._rigCameras[index]);
  23615. }
  23616. this.activeCamera = camera;
  23617. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23618. };
  23619. Scene.prototype._checkIntersections = function () {
  23620. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23621. var sourceMesh = this._meshesForIntersections.data[index];
  23622. if (!sourceMesh.actionManager) {
  23623. continue;
  23624. }
  23625. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23626. var action = sourceMesh.actionManager.actions[actionIndex];
  23627. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23628. var parameters = action.getTriggerParameter();
  23629. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23630. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23631. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23632. if (areIntersecting && currentIntersectionInProgress === -1) {
  23633. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23634. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23635. sourceMesh._intersectionsInProgress.push(otherMesh);
  23636. }
  23637. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23638. sourceMesh._intersectionsInProgress.push(otherMesh);
  23639. }
  23640. }
  23641. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23642. //They intersected, and now they don't.
  23643. //is this trigger an exit trigger? execute an event.
  23644. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23645. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23646. }
  23647. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23648. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23649. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23650. }
  23651. }
  23652. }
  23653. }
  23654. }
  23655. };
  23656. Scene.prototype.render = function () {
  23657. if (this.isDisposed) {
  23658. return;
  23659. }
  23660. this._activeParticles.fetchNewFrame();
  23661. this._totalVertices.fetchNewFrame();
  23662. this._activeIndices.fetchNewFrame();
  23663. this._activeBones.fetchNewFrame();
  23664. this._meshesForIntersections.reset();
  23665. this.resetCachedMaterial();
  23666. this.onBeforeAnimationsObservable.notifyObservers(this);
  23667. // Actions
  23668. if (this.actionManager) {
  23669. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23670. }
  23671. //Simplification Queue
  23672. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23673. this.simplificationQueue.executeNext();
  23674. }
  23675. if (this._engine.isDeterministicLockStep()) {
  23676. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23677. var defaultFPS = (60.0 / 1000.0);
  23678. var defaultFrameTime = 1000 / 60; // frame time in MS
  23679. if (this._physicsEngine) {
  23680. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23681. }
  23682. var stepsTaken = 0;
  23683. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23684. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23685. internalSteps = Math.min(internalSteps, maxSubSteps);
  23686. do {
  23687. this.onBeforeStepObservable.notifyObservers(this);
  23688. // Animations
  23689. this._animationRatio = defaultFrameTime * defaultFPS;
  23690. this._animate();
  23691. this.onAfterAnimationsObservable.notifyObservers(this);
  23692. // Physics
  23693. if (this._physicsEngine) {
  23694. this.onBeforePhysicsObservable.notifyObservers(this);
  23695. this._physicsEngine._step(defaultFrameTime / 1000);
  23696. this.onAfterPhysicsObservable.notifyObservers(this);
  23697. }
  23698. this.onAfterStepObservable.notifyObservers(this);
  23699. this._currentStepId++;
  23700. stepsTaken++;
  23701. deltaTime -= defaultFrameTime;
  23702. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23703. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23704. }
  23705. else {
  23706. // Animations
  23707. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23708. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23709. this._animate();
  23710. this.onAfterAnimationsObservable.notifyObservers(this);
  23711. // Physics
  23712. if (this._physicsEngine) {
  23713. this.onBeforePhysicsObservable.notifyObservers(this);
  23714. this._physicsEngine._step(deltaTime / 1000.0);
  23715. this.onAfterPhysicsObservable.notifyObservers(this);
  23716. }
  23717. }
  23718. // update gamepad manager
  23719. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23720. this._gamepadManager._checkGamepadsStatus();
  23721. }
  23722. // Before render
  23723. this.onBeforeRenderObservable.notifyObservers(this);
  23724. // Customs render targets
  23725. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23726. var engine = this.getEngine();
  23727. var currentActiveCamera = this.activeCamera;
  23728. if (this.renderTargetsEnabled) {
  23729. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23730. this._intermediateRendering = true;
  23731. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23732. var renderTarget = this.customRenderTargets[customIndex];
  23733. if (renderTarget._shouldRender()) {
  23734. this._renderId++;
  23735. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23736. if (!this.activeCamera)
  23737. throw new Error("Active camera not set");
  23738. // Viewport
  23739. engine.setViewport(this.activeCamera.viewport);
  23740. // Camera
  23741. this.updateTransformMatrix();
  23742. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23743. }
  23744. }
  23745. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23746. this._intermediateRendering = false;
  23747. this._renderId++;
  23748. }
  23749. // Restore back buffer
  23750. if (this.customRenderTargets.length > 0) {
  23751. engine.restoreDefaultFramebuffer();
  23752. }
  23753. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23754. this.activeCamera = currentActiveCamera;
  23755. // Procedural textures
  23756. if (this.proceduralTexturesEnabled) {
  23757. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23758. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23759. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23760. if (proceduralTexture._shouldRender()) {
  23761. proceduralTexture.render();
  23762. }
  23763. }
  23764. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23765. }
  23766. // Clear
  23767. if (this.autoClearDepthAndStencil || this.autoClear) {
  23768. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  23769. }
  23770. // Shadows
  23771. if (this.shadowsEnabled) {
  23772. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  23773. var light = this.lights[lightIndex];
  23774. var shadowGenerator = light.getShadowGenerator();
  23775. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  23776. var shadowMap = (shadowGenerator.getShadowMap());
  23777. if (this.textures.indexOf(shadowMap) !== -1) {
  23778. this._renderTargets.push(shadowMap);
  23779. }
  23780. }
  23781. }
  23782. }
  23783. // Depth renderer
  23784. if (this._depthRenderer) {
  23785. this._renderTargets.push(this._depthRenderer.getDepthMap());
  23786. }
  23787. // Geometry renderer
  23788. if (this._geometryBufferRenderer) {
  23789. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  23790. }
  23791. // RenderPipeline
  23792. if (this._postProcessRenderPipelineManager) {
  23793. this._postProcessRenderPipelineManager.update();
  23794. }
  23795. // Multi-cameras?
  23796. if (this.activeCameras.length > 0) {
  23797. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  23798. if (cameraIndex > 0) {
  23799. this._engine.clear(null, false, true, true);
  23800. }
  23801. this._processSubCameras(this.activeCameras[cameraIndex]);
  23802. }
  23803. }
  23804. else {
  23805. if (!this.activeCamera) {
  23806. throw new Error("No camera defined");
  23807. }
  23808. this._processSubCameras(this.activeCamera);
  23809. }
  23810. // Intersection checks
  23811. this._checkIntersections();
  23812. // Update the audio listener attached to the camera
  23813. if (BABYLON.AudioEngine) {
  23814. this._updateAudioParameters();
  23815. }
  23816. // After render
  23817. if (this.afterRender) {
  23818. this.afterRender();
  23819. }
  23820. this.onAfterRenderObservable.notifyObservers(this);
  23821. // Cleaning
  23822. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23823. var data = this._toBeDisposed.data[index];
  23824. if (data) {
  23825. data.dispose();
  23826. }
  23827. this._toBeDisposed[index] = null;
  23828. }
  23829. this._toBeDisposed.reset();
  23830. if (this.dumpNextRenderTargets) {
  23831. this.dumpNextRenderTargets = false;
  23832. }
  23833. this._activeBones.addCount(0, true);
  23834. this._activeIndices.addCount(0, true);
  23835. this._activeParticles.addCount(0, true);
  23836. };
  23837. Scene.prototype._updateAudioParameters = function () {
  23838. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23839. return;
  23840. }
  23841. var listeningCamera;
  23842. var audioEngine = BABYLON.Engine.audioEngine;
  23843. if (this.activeCameras.length > 0) {
  23844. listeningCamera = this.activeCameras[0];
  23845. }
  23846. else {
  23847. listeningCamera = this.activeCamera;
  23848. }
  23849. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23850. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23851. // for VR cameras
  23852. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23853. listeningCamera = listeningCamera.rigCameras[0];
  23854. }
  23855. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23856. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23857. cameraDirection.normalize();
  23858. // To avoid some errors on GearVR
  23859. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23860. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23861. }
  23862. var i;
  23863. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23864. var sound = this.mainSoundTrack.soundCollection[i];
  23865. if (sound.useCustomAttenuation) {
  23866. sound.updateDistanceFromListener();
  23867. }
  23868. }
  23869. for (i = 0; i < this.soundTracks.length; i++) {
  23870. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23871. sound = this.soundTracks[i].soundCollection[j];
  23872. if (sound.useCustomAttenuation) {
  23873. sound.updateDistanceFromListener();
  23874. }
  23875. }
  23876. }
  23877. }
  23878. };
  23879. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23880. // Audio
  23881. get: function () {
  23882. return this._audioEnabled;
  23883. },
  23884. set: function (value) {
  23885. this._audioEnabled = value;
  23886. if (BABYLON.AudioEngine) {
  23887. if (this._audioEnabled) {
  23888. this._enableAudio();
  23889. }
  23890. else {
  23891. this._disableAudio();
  23892. }
  23893. }
  23894. },
  23895. enumerable: true,
  23896. configurable: true
  23897. });
  23898. Scene.prototype._disableAudio = function () {
  23899. var i;
  23900. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23901. this.mainSoundTrack.soundCollection[i].pause();
  23902. }
  23903. for (i = 0; i < this.soundTracks.length; i++) {
  23904. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23905. this.soundTracks[i].soundCollection[j].pause();
  23906. }
  23907. }
  23908. };
  23909. Scene.prototype._enableAudio = function () {
  23910. var i;
  23911. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23912. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  23913. this.mainSoundTrack.soundCollection[i].play();
  23914. }
  23915. }
  23916. for (i = 0; i < this.soundTracks.length; i++) {
  23917. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23918. if (this.soundTracks[i].soundCollection[j].isPaused) {
  23919. this.soundTracks[i].soundCollection[j].play();
  23920. }
  23921. }
  23922. }
  23923. };
  23924. Object.defineProperty(Scene.prototype, "headphone", {
  23925. get: function () {
  23926. return this._headphone;
  23927. },
  23928. set: function (value) {
  23929. this._headphone = value;
  23930. if (BABYLON.AudioEngine) {
  23931. if (this._headphone) {
  23932. this._switchAudioModeForHeadphones();
  23933. }
  23934. else {
  23935. this._switchAudioModeForNormalSpeakers();
  23936. }
  23937. }
  23938. },
  23939. enumerable: true,
  23940. configurable: true
  23941. });
  23942. Scene.prototype._switchAudioModeForHeadphones = function () {
  23943. this.mainSoundTrack.switchPanningModelToHRTF();
  23944. for (var i = 0; i < this.soundTracks.length; i++) {
  23945. this.soundTracks[i].switchPanningModelToHRTF();
  23946. }
  23947. };
  23948. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  23949. this.mainSoundTrack.switchPanningModelToEqualPower();
  23950. for (var i = 0; i < this.soundTracks.length; i++) {
  23951. this.soundTracks[i].switchPanningModelToEqualPower();
  23952. }
  23953. };
  23954. Scene.prototype.enableDepthRenderer = function () {
  23955. if (this._depthRenderer) {
  23956. return this._depthRenderer;
  23957. }
  23958. this._depthRenderer = new BABYLON.DepthRenderer(this);
  23959. return this._depthRenderer;
  23960. };
  23961. Scene.prototype.disableDepthRenderer = function () {
  23962. if (!this._depthRenderer) {
  23963. return;
  23964. }
  23965. this._depthRenderer.dispose();
  23966. this._depthRenderer = null;
  23967. };
  23968. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  23969. if (ratio === void 0) { ratio = 1; }
  23970. if (this._geometryBufferRenderer) {
  23971. return this._geometryBufferRenderer;
  23972. }
  23973. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  23974. if (!this._geometryBufferRenderer.isSupported) {
  23975. this._geometryBufferRenderer = null;
  23976. }
  23977. return this._geometryBufferRenderer;
  23978. };
  23979. Scene.prototype.disableGeometryBufferRenderer = function () {
  23980. if (!this._geometryBufferRenderer) {
  23981. return;
  23982. }
  23983. this._geometryBufferRenderer.dispose();
  23984. this._geometryBufferRenderer = null;
  23985. };
  23986. Scene.prototype.freezeMaterials = function () {
  23987. for (var i = 0; i < this.materials.length; i++) {
  23988. this.materials[i].freeze();
  23989. }
  23990. };
  23991. Scene.prototype.unfreezeMaterials = function () {
  23992. for (var i = 0; i < this.materials.length; i++) {
  23993. this.materials[i].unfreeze();
  23994. }
  23995. };
  23996. Scene.prototype.dispose = function () {
  23997. this.beforeRender = null;
  23998. this.afterRender = null;
  23999. this.skeletons = [];
  24000. this.morphTargetManagers = [];
  24001. this.importedMeshesFiles = new Array();
  24002. this.stopAllAnimations();
  24003. this.resetCachedMaterial();
  24004. if (this._depthRenderer) {
  24005. this._depthRenderer.dispose();
  24006. }
  24007. if (this._gamepadManager) {
  24008. this._gamepadManager.dispose();
  24009. this._gamepadManager = null;
  24010. }
  24011. // Smart arrays
  24012. if (this.activeCamera) {
  24013. this.activeCamera._activeMeshes.dispose();
  24014. this.activeCamera = null;
  24015. }
  24016. this._activeMeshes.dispose();
  24017. this._renderingManager.dispose();
  24018. this._processedMaterials.dispose();
  24019. this._activeParticleSystems.dispose();
  24020. this._activeSkeletons.dispose();
  24021. this._softwareSkinnedMeshes.dispose();
  24022. this._renderTargets.dispose();
  24023. if (this._boundingBoxRenderer) {
  24024. this._boundingBoxRenderer.dispose();
  24025. }
  24026. this._meshesForIntersections.dispose();
  24027. this._toBeDisposed.dispose();
  24028. // Abort active requests
  24029. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24030. var request = _a[_i];
  24031. request.abort();
  24032. }
  24033. // Debug layer
  24034. if (this._debugLayer) {
  24035. this._debugLayer.hide();
  24036. }
  24037. // Events
  24038. this.onDisposeObservable.notifyObservers(this);
  24039. this.onDisposeObservable.clear();
  24040. this.onBeforeRenderObservable.clear();
  24041. this.onAfterRenderObservable.clear();
  24042. this.OnBeforeRenderTargetsRenderObservable.clear();
  24043. this.OnAfterRenderTargetsRenderObservable.clear();
  24044. this.onAfterStepObservable.clear();
  24045. this.onBeforeStepObservable.clear();
  24046. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24047. this.onAfterActiveMeshesEvaluationObservable.clear();
  24048. this.onBeforeParticlesRenderingObservable.clear();
  24049. this.onAfterParticlesRenderingObservable.clear();
  24050. this.onBeforeSpritesRenderingObservable.clear();
  24051. this.onAfterSpritesRenderingObservable.clear();
  24052. this.onBeforeDrawPhaseObservable.clear();
  24053. this.onAfterDrawPhaseObservable.clear();
  24054. this.onBeforePhysicsObservable.clear();
  24055. this.onAfterPhysicsObservable.clear();
  24056. this.onBeforeAnimationsObservable.clear();
  24057. this.onAfterAnimationsObservable.clear();
  24058. this.onDataLoadedObservable.clear();
  24059. this.detachControl();
  24060. // Release sounds & sounds tracks
  24061. if (BABYLON.AudioEngine) {
  24062. this.disposeSounds();
  24063. }
  24064. // VR Helper
  24065. if (this.VRHelper) {
  24066. this.VRHelper.dispose();
  24067. }
  24068. // Detach cameras
  24069. var canvas = this._engine.getRenderingCanvas();
  24070. if (canvas) {
  24071. var index;
  24072. for (index = 0; index < this.cameras.length; index++) {
  24073. this.cameras[index].detachControl(canvas);
  24074. }
  24075. }
  24076. // Release animation groups
  24077. while (this.animationGroups.length) {
  24078. this.animationGroups[0].dispose();
  24079. }
  24080. // Release lights
  24081. while (this.lights.length) {
  24082. this.lights[0].dispose();
  24083. }
  24084. // Release meshes
  24085. while (this.meshes.length) {
  24086. this.meshes[0].dispose(true);
  24087. }
  24088. while (this.transformNodes.length) {
  24089. this.removeTransformNode(this.transformNodes[0]);
  24090. }
  24091. // Release cameras
  24092. while (this.cameras.length) {
  24093. this.cameras[0].dispose();
  24094. }
  24095. // Release materials
  24096. if (this.defaultMaterial) {
  24097. this.defaultMaterial.dispose();
  24098. }
  24099. while (this.multiMaterials.length) {
  24100. this.multiMaterials[0].dispose();
  24101. }
  24102. while (this.materials.length) {
  24103. this.materials[0].dispose();
  24104. }
  24105. // Release particles
  24106. while (this.particleSystems.length) {
  24107. this.particleSystems[0].dispose();
  24108. }
  24109. // Release sprites
  24110. while (this.spriteManagers.length) {
  24111. this.spriteManagers[0].dispose();
  24112. }
  24113. // Release postProcesses
  24114. while (this.postProcesses.length) {
  24115. this.postProcesses[0].dispose();
  24116. }
  24117. // Release layers
  24118. while (this.layers.length) {
  24119. this.layers[0].dispose();
  24120. }
  24121. while (this.effectLayers.length) {
  24122. this.effectLayers[0].dispose();
  24123. }
  24124. // Release textures
  24125. while (this.textures.length) {
  24126. this.textures[0].dispose();
  24127. }
  24128. // Release UBO
  24129. this._sceneUbo.dispose();
  24130. if (this._alternateSceneUbo) {
  24131. this._alternateSceneUbo.dispose();
  24132. }
  24133. // Post-processes
  24134. this.postProcessManager.dispose();
  24135. if (this._postProcessRenderPipelineManager) {
  24136. this._postProcessRenderPipelineManager.dispose();
  24137. }
  24138. // Physics
  24139. if (this._physicsEngine) {
  24140. this.disablePhysicsEngine();
  24141. }
  24142. // Remove from engine
  24143. index = this._engine.scenes.indexOf(this);
  24144. if (index > -1) {
  24145. this._engine.scenes.splice(index, 1);
  24146. }
  24147. this._engine.wipeCaches(true);
  24148. this._isDisposed = true;
  24149. };
  24150. Object.defineProperty(Scene.prototype, "isDisposed", {
  24151. get: function () {
  24152. return this._isDisposed;
  24153. },
  24154. enumerable: true,
  24155. configurable: true
  24156. });
  24157. // Release sounds & sounds tracks
  24158. Scene.prototype.disposeSounds = function () {
  24159. if (!this._mainSoundTrack) {
  24160. return;
  24161. }
  24162. this.mainSoundTrack.dispose();
  24163. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24164. this.soundTracks[scIndex].dispose();
  24165. }
  24166. };
  24167. // Octrees
  24168. Scene.prototype.getWorldExtends = function () {
  24169. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24170. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24171. for (var index = 0; index < this.meshes.length; index++) {
  24172. var mesh = this.meshes[index];
  24173. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24174. continue;
  24175. }
  24176. mesh.computeWorldMatrix(true);
  24177. var boundingInfo = mesh.getBoundingInfo();
  24178. var minBox = boundingInfo.boundingBox.minimumWorld;
  24179. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24180. BABYLON.Tools.CheckExtends(minBox, min, max);
  24181. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24182. }
  24183. return {
  24184. min: min,
  24185. max: max
  24186. };
  24187. };
  24188. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24189. if (maxCapacity === void 0) { maxCapacity = 64; }
  24190. if (maxDepth === void 0) { maxDepth = 2; }
  24191. if (!this._selectionOctree) {
  24192. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24193. }
  24194. var worldExtends = this.getWorldExtends();
  24195. // Update octree
  24196. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24197. return this._selectionOctree;
  24198. };
  24199. // Picking
  24200. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24201. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24202. var result = BABYLON.Ray.Zero();
  24203. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24204. return result;
  24205. };
  24206. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24207. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24208. var engine = this._engine;
  24209. if (!camera) {
  24210. if (!this.activeCamera)
  24211. throw new Error("Active camera not set");
  24212. camera = this.activeCamera;
  24213. }
  24214. var cameraViewport = camera.viewport;
  24215. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24216. // Moving coordinates to local viewport world
  24217. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24218. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24219. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24220. return this;
  24221. };
  24222. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24223. var result = BABYLON.Ray.Zero();
  24224. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24225. return result;
  24226. };
  24227. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24228. if (!BABYLON.PickingInfo) {
  24229. return this;
  24230. }
  24231. var engine = this._engine;
  24232. if (!camera) {
  24233. if (!this.activeCamera)
  24234. throw new Error("Active camera not set");
  24235. camera = this.activeCamera;
  24236. }
  24237. var cameraViewport = camera.viewport;
  24238. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24239. var identity = BABYLON.Matrix.Identity();
  24240. // Moving coordinates to local viewport world
  24241. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24242. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24243. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24244. return this;
  24245. };
  24246. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24247. if (!BABYLON.PickingInfo) {
  24248. return null;
  24249. }
  24250. var pickingInfo = null;
  24251. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24252. var mesh = this.meshes[meshIndex];
  24253. if (predicate) {
  24254. if (!predicate(mesh)) {
  24255. continue;
  24256. }
  24257. }
  24258. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24259. continue;
  24260. }
  24261. var world = mesh.getWorldMatrix();
  24262. var ray = rayFunction(world);
  24263. var result = mesh.intersects(ray, fastCheck);
  24264. if (!result || !result.hit)
  24265. continue;
  24266. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24267. continue;
  24268. pickingInfo = result;
  24269. if (fastCheck) {
  24270. break;
  24271. }
  24272. }
  24273. return pickingInfo || new BABYLON.PickingInfo();
  24274. };
  24275. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24276. if (!BABYLON.PickingInfo) {
  24277. return null;
  24278. }
  24279. var pickingInfos = new Array();
  24280. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24281. var mesh = this.meshes[meshIndex];
  24282. if (predicate) {
  24283. if (!predicate(mesh)) {
  24284. continue;
  24285. }
  24286. }
  24287. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24288. continue;
  24289. }
  24290. var world = mesh.getWorldMatrix();
  24291. var ray = rayFunction(world);
  24292. var result = mesh.intersects(ray, false);
  24293. if (!result || !result.hit)
  24294. continue;
  24295. pickingInfos.push(result);
  24296. }
  24297. return pickingInfos;
  24298. };
  24299. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24300. if (!BABYLON.PickingInfo) {
  24301. return null;
  24302. }
  24303. var pickingInfo = null;
  24304. if (!camera) {
  24305. if (!this.activeCamera) {
  24306. return null;
  24307. }
  24308. camera = this.activeCamera;
  24309. }
  24310. if (this.spriteManagers.length > 0) {
  24311. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24312. var spriteManager = this.spriteManagers[spriteIndex];
  24313. if (!spriteManager.isPickable) {
  24314. continue;
  24315. }
  24316. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24317. if (!result || !result.hit)
  24318. continue;
  24319. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24320. continue;
  24321. pickingInfo = result;
  24322. if (fastCheck) {
  24323. break;
  24324. }
  24325. }
  24326. }
  24327. return pickingInfo || new BABYLON.PickingInfo();
  24328. };
  24329. /** Launch a ray to try to pick a mesh in the scene
  24330. * @param x position on screen
  24331. * @param y position on screen
  24332. * @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
  24333. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24334. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24335. */
  24336. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24337. var _this = this;
  24338. if (!BABYLON.PickingInfo) {
  24339. return null;
  24340. }
  24341. return this._internalPick(function (world) {
  24342. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24343. return _this._tempPickingRay;
  24344. }, predicate, fastCheck);
  24345. };
  24346. /** Launch a ray to try to pick a sprite in the scene
  24347. * @param x position on screen
  24348. * @param y position on screen
  24349. * @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
  24350. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24351. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24352. */
  24353. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24354. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24355. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24356. };
  24357. /** Use the given ray to pick a mesh in the scene
  24358. * @param ray The ray to use to pick meshes
  24359. * @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
  24360. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24361. */
  24362. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24363. var _this = this;
  24364. return this._internalPick(function (world) {
  24365. if (!_this._pickWithRayInverseMatrix) {
  24366. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24367. }
  24368. world.invertToRef(_this._pickWithRayInverseMatrix);
  24369. if (!_this._cachedRayForTransform) {
  24370. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24371. }
  24372. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24373. return _this._cachedRayForTransform;
  24374. }, predicate, fastCheck);
  24375. };
  24376. /**
  24377. * Launch a ray to try to pick a mesh in the scene
  24378. * @param x X position on screen
  24379. * @param y Y position on screen
  24380. * @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
  24381. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24382. */
  24383. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24384. var _this = this;
  24385. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24386. };
  24387. /**
  24388. * Launch a ray to try to pick a mesh in the scene
  24389. * @param ray Ray to use
  24390. * @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
  24391. */
  24392. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24393. var _this = this;
  24394. return this._internalMultiPick(function (world) {
  24395. if (!_this._pickWithRayInverseMatrix) {
  24396. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24397. }
  24398. world.invertToRef(_this._pickWithRayInverseMatrix);
  24399. if (!_this._cachedRayForTransform) {
  24400. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24401. }
  24402. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24403. return _this._cachedRayForTransform;
  24404. }, predicate);
  24405. };
  24406. Scene.prototype.setPointerOverMesh = function (mesh) {
  24407. if (this._pointerOverMesh === mesh) {
  24408. return;
  24409. }
  24410. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24411. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24412. }
  24413. this._pointerOverMesh = mesh;
  24414. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24415. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24416. }
  24417. };
  24418. Scene.prototype.getPointerOverMesh = function () {
  24419. return this._pointerOverMesh;
  24420. };
  24421. Scene.prototype.setPointerOverSprite = function (sprite) {
  24422. if (this._pointerOverSprite === sprite) {
  24423. return;
  24424. }
  24425. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24426. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24427. }
  24428. this._pointerOverSprite = sprite;
  24429. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24430. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24431. }
  24432. };
  24433. Scene.prototype.getPointerOverSprite = function () {
  24434. return this._pointerOverSprite;
  24435. };
  24436. // Physics
  24437. Scene.prototype.getPhysicsEngine = function () {
  24438. return this._physicsEngine;
  24439. };
  24440. /**
  24441. * Enables physics to the current scene
  24442. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24443. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24444. * @return {boolean} was the physics engine initialized
  24445. */
  24446. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24447. if (gravity === void 0) { gravity = null; }
  24448. if (this._physicsEngine) {
  24449. return true;
  24450. }
  24451. try {
  24452. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24453. return true;
  24454. }
  24455. catch (e) {
  24456. BABYLON.Tools.Error(e.message);
  24457. return false;
  24458. }
  24459. };
  24460. Scene.prototype.disablePhysicsEngine = function () {
  24461. if (!this._physicsEngine) {
  24462. return;
  24463. }
  24464. this._physicsEngine.dispose();
  24465. this._physicsEngine = null;
  24466. };
  24467. Scene.prototype.isPhysicsEnabled = function () {
  24468. return this._physicsEngine !== undefined;
  24469. };
  24470. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24471. var mesh = compound.parts[0].mesh;
  24472. if (mesh.physicsImpostor) {
  24473. mesh.physicsImpostor.dispose();
  24474. mesh.physicsImpostor = null;
  24475. }
  24476. };
  24477. // Misc.
  24478. Scene.prototype._rebuildGeometries = function () {
  24479. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24480. var geometry = _a[_i];
  24481. geometry._rebuild();
  24482. }
  24483. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24484. var mesh = _c[_b];
  24485. mesh._rebuild();
  24486. }
  24487. if (this.postProcessManager) {
  24488. this.postProcessManager._rebuild();
  24489. }
  24490. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24491. var layer = _e[_d];
  24492. layer._rebuild();
  24493. }
  24494. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  24495. var effectLayer = _g[_f];
  24496. effectLayer._rebuild();
  24497. }
  24498. if (this._boundingBoxRenderer) {
  24499. this._boundingBoxRenderer._rebuild();
  24500. }
  24501. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24502. var system = _j[_h];
  24503. system.rebuild();
  24504. }
  24505. if (this._postProcessRenderPipelineManager) {
  24506. this._postProcessRenderPipelineManager._rebuild();
  24507. }
  24508. };
  24509. Scene.prototype._rebuildTextures = function () {
  24510. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24511. var texture = _a[_i];
  24512. texture._rebuild();
  24513. }
  24514. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24515. };
  24516. /**
  24517. * Creates a default light for the scene.
  24518. * @param replace Whether to replace the existing lights in the scene.
  24519. */
  24520. Scene.prototype.createDefaultLight = function (replace) {
  24521. if (replace === void 0) { replace = false; }
  24522. // Dispose existing light in replace mode.
  24523. if (replace) {
  24524. if (this.lights) {
  24525. for (var i = 0; i < this.lights.length; i++) {
  24526. this.lights[i].dispose();
  24527. }
  24528. }
  24529. }
  24530. // Light
  24531. if (this.lights.length === 0) {
  24532. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24533. }
  24534. };
  24535. /**
  24536. * Creates a default camera for the scene.
  24537. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24538. * @param replace Whether to replace the existing active camera in the scene.
  24539. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24540. */
  24541. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24542. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24543. if (replace === void 0) { replace = false; }
  24544. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24545. // Dispose existing camera in replace mode.
  24546. if (replace) {
  24547. if (this.activeCamera) {
  24548. this.activeCamera.dispose();
  24549. this.activeCamera = null;
  24550. }
  24551. }
  24552. // Camera
  24553. if (!this.activeCamera) {
  24554. var worldExtends = this.getWorldExtends();
  24555. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24556. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24557. var camera;
  24558. var radius = worldSize.length() * 1.5;
  24559. // empty scene scenario!
  24560. if (!isFinite(radius)) {
  24561. radius = 1;
  24562. worldCenter.copyFromFloats(0, 0, 0);
  24563. }
  24564. if (createArcRotateCamera) {
  24565. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24566. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24567. arcRotateCamera.wheelPrecision = 100 / radius;
  24568. camera = arcRotateCamera;
  24569. }
  24570. else {
  24571. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24572. freeCamera.setTarget(worldCenter);
  24573. camera = freeCamera;
  24574. }
  24575. camera.minZ = radius * 0.01;
  24576. camera.maxZ = radius * 1000;
  24577. camera.speed = radius * 0.2;
  24578. this.activeCamera = camera;
  24579. var canvas = this.getEngine().getRenderingCanvas();
  24580. if (attachCameraControls && canvas) {
  24581. camera.attachControl(canvas);
  24582. }
  24583. }
  24584. };
  24585. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24586. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24587. if (replace === void 0) { replace = false; }
  24588. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24589. this.createDefaultLight(replace);
  24590. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24591. };
  24592. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24593. if (pbr === void 0) { pbr = false; }
  24594. if (scale === void 0) { scale = 1000; }
  24595. if (blur === void 0) { blur = 0; }
  24596. if (environmentTexture) {
  24597. this.environmentTexture = environmentTexture;
  24598. }
  24599. if (!this.environmentTexture) {
  24600. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24601. return null;
  24602. }
  24603. // Skybox
  24604. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24605. if (pbr) {
  24606. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24607. hdrSkyboxMaterial.backFaceCulling = false;
  24608. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24609. if (hdrSkyboxMaterial.reflectionTexture) {
  24610. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24611. }
  24612. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24613. hdrSkyboxMaterial.disableLighting = true;
  24614. hdrSkyboxMaterial.twoSidedLighting = true;
  24615. hdrSkybox.infiniteDistance = true;
  24616. hdrSkybox.material = hdrSkyboxMaterial;
  24617. }
  24618. else {
  24619. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24620. skyboxMaterial.backFaceCulling = false;
  24621. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24622. if (skyboxMaterial.reflectionTexture) {
  24623. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24624. }
  24625. skyboxMaterial.disableLighting = true;
  24626. hdrSkybox.infiniteDistance = true;
  24627. hdrSkybox.material = skyboxMaterial;
  24628. }
  24629. return hdrSkybox;
  24630. };
  24631. Scene.prototype.createDefaultEnvironment = function (options) {
  24632. if (BABYLON.EnvironmentHelper) {
  24633. return new BABYLON.EnvironmentHelper(options, this);
  24634. }
  24635. return null;
  24636. };
  24637. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24638. if (webVROptions === void 0) { webVROptions = {}; }
  24639. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24640. };
  24641. // Tags
  24642. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24643. if (tagsQuery === undefined) {
  24644. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24645. return list;
  24646. }
  24647. var listByTags = [];
  24648. forEach = forEach || (function (item) { return; });
  24649. for (var i in list) {
  24650. var item = list[i];
  24651. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24652. listByTags.push(item);
  24653. forEach(item);
  24654. }
  24655. }
  24656. return listByTags;
  24657. };
  24658. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24659. return this._getByTags(this.meshes, tagsQuery, forEach);
  24660. };
  24661. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24662. return this._getByTags(this.cameras, tagsQuery, forEach);
  24663. };
  24664. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24665. return this._getByTags(this.lights, tagsQuery, forEach);
  24666. };
  24667. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24668. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24669. };
  24670. /**
  24671. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24672. * This allowed control for front to back rendering or reversly depending of the special needs.
  24673. *
  24674. * @param renderingGroupId The rendering group id corresponding to its index
  24675. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24676. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24677. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24678. */
  24679. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24680. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24681. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24682. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24683. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24684. };
  24685. /**
  24686. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24687. *
  24688. * @param renderingGroupId The rendering group id corresponding to its index
  24689. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24690. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24691. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24692. */
  24693. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24694. if (depth === void 0) { depth = true; }
  24695. if (stencil === void 0) { stencil = true; }
  24696. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24697. };
  24698. /**
  24699. * Will flag all materials as dirty to trigger new shader compilation
  24700. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24701. */
  24702. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24703. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24704. var material = _a[_i];
  24705. if (predicate && !predicate(material)) {
  24706. continue;
  24707. }
  24708. material.markAsDirty(flag);
  24709. }
  24710. };
  24711. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24712. var _this = this;
  24713. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24714. this._activeRequests.push(request);
  24715. request.onCompleteObservable.add(function (request) {
  24716. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24717. });
  24718. return request;
  24719. };
  24720. /** @ignore */
  24721. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24722. var _this = this;
  24723. return new Promise(function (resolve, reject) {
  24724. _this._loadFile(url, function (data) {
  24725. resolve(data);
  24726. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24727. reject(exception);
  24728. });
  24729. });
  24730. };
  24731. // Statics
  24732. Scene._FOGMODE_NONE = 0;
  24733. Scene._FOGMODE_EXP = 1;
  24734. Scene._FOGMODE_EXP2 = 2;
  24735. Scene._FOGMODE_LINEAR = 3;
  24736. Scene._uniqueIdCounter = 0;
  24737. Scene.MinDeltaTime = 1.0;
  24738. Scene.MaxDeltaTime = 1000.0;
  24739. /** The distance in pixel that you have to move to prevent some events */
  24740. Scene.DragMovementThreshold = 10; // in pixels
  24741. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24742. Scene.LongPressDelay = 500; // in milliseconds
  24743. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24744. Scene.DoubleClickDelay = 300; // in milliseconds
  24745. /** If you need to check double click without raising a single click at first click, enable this flag */
  24746. Scene.ExclusiveDoubleClickMode = false;
  24747. return Scene;
  24748. }());
  24749. BABYLON.Scene = Scene;
  24750. })(BABYLON || (BABYLON = {}));
  24751. //# sourceMappingURL=babylon.scene.js.map
  24752. var BABYLON;
  24753. (function (BABYLON) {
  24754. /**
  24755. * Set of assets to keep when moving a scene into an asset container.
  24756. */
  24757. var KeepAssets = /** @class */ (function () {
  24758. function KeepAssets() {
  24759. /**
  24760. * Cameras to keep.
  24761. */
  24762. this.cameras = new Array();
  24763. /**
  24764. * Lights to keep.
  24765. */
  24766. this.lights = new Array();
  24767. /**
  24768. * Meshes to keep.
  24769. */
  24770. this.meshes = new Array();
  24771. /**
  24772. * Skeletons to keep.
  24773. */
  24774. this.skeletons = new Array();
  24775. /**
  24776. * ParticleSystems to keep.
  24777. */
  24778. this.particleSystems = new Array();
  24779. /**
  24780. * Animations to keep.
  24781. */
  24782. this.animations = new Array();
  24783. /**
  24784. * MultiMaterials to keep.
  24785. */
  24786. this.multiMaterials = new Array();
  24787. /**
  24788. * Materials to keep.
  24789. */
  24790. this.materials = new Array();
  24791. /**
  24792. * MorphTargetManagers to keep.
  24793. */
  24794. this.morphTargetManagers = new Array();
  24795. /**
  24796. * Geometries to keep.
  24797. */
  24798. this.geometries = new Array();
  24799. /**
  24800. * TransformNodes to keep.
  24801. */
  24802. this.transformNodes = new Array();
  24803. /**
  24804. * LensFlareSystems to keep.
  24805. */
  24806. this.lensFlareSystems = new Array();
  24807. /**
  24808. * ShadowGenerators to keep.
  24809. */
  24810. this.shadowGenerators = new Array();
  24811. /**
  24812. * ActionManagers to keep.
  24813. */
  24814. this.actionManagers = new Array();
  24815. /**
  24816. * Sounds to keep.
  24817. */
  24818. this.sounds = new Array();
  24819. }
  24820. return KeepAssets;
  24821. }());
  24822. BABYLON.KeepAssets = KeepAssets;
  24823. /**
  24824. * Container with a set of assets that can be added or removed from a scene.
  24825. */
  24826. var AssetContainer = /** @class */ (function () {
  24827. /**
  24828. * Instantiates an AssetContainer.
  24829. * @param scene The scene the AssetContainer belongs to.
  24830. */
  24831. function AssetContainer(scene) {
  24832. // Objects
  24833. /**
  24834. * Cameras populated in the container.
  24835. */
  24836. this.cameras = new Array();
  24837. /**
  24838. * Lights populated in the container.
  24839. */
  24840. this.lights = new Array();
  24841. /**
  24842. * Meshes populated in the container.
  24843. */
  24844. this.meshes = new Array();
  24845. /**
  24846. * Skeletons populated in the container.
  24847. */
  24848. this.skeletons = new Array();
  24849. /**
  24850. * ParticleSystems populated in the container.
  24851. */
  24852. this.particleSystems = new Array();
  24853. /**
  24854. * Animations populated in the container.
  24855. */
  24856. this.animations = new Array();
  24857. /**
  24858. * MultiMaterials populated in the container.
  24859. */
  24860. this.multiMaterials = new Array();
  24861. /**
  24862. * Materials populated in the container.
  24863. */
  24864. this.materials = new Array();
  24865. /**
  24866. * MorphTargetManagers populated in the container.
  24867. */
  24868. this.morphTargetManagers = new Array();
  24869. /**
  24870. * Geometries populated in the container.
  24871. */
  24872. this.geometries = new Array();
  24873. /**
  24874. * TransformNodes populated in the container.
  24875. */
  24876. this.transformNodes = new Array();
  24877. /**
  24878. * LensFlareSystems populated in the container.
  24879. */
  24880. this.lensFlareSystems = new Array();
  24881. /**
  24882. * ShadowGenerators populated in the container.
  24883. */
  24884. this.shadowGenerators = new Array();
  24885. /**
  24886. * ActionManagers populated in the container.
  24887. */
  24888. this.actionManagers = new Array();
  24889. /**
  24890. * Sounds populated in the container.
  24891. */
  24892. this.sounds = new Array();
  24893. this.scene = scene;
  24894. }
  24895. /**
  24896. * Adds all the assets from the container to the scene.
  24897. */
  24898. AssetContainer.prototype.addAllToScene = function () {
  24899. var _this = this;
  24900. this.cameras.forEach(function (o) {
  24901. _this.scene.addCamera(o);
  24902. });
  24903. this.lights.forEach(function (o) {
  24904. _this.scene.addLight(o);
  24905. });
  24906. this.meshes.forEach(function (o) {
  24907. _this.scene.addMesh(o);
  24908. });
  24909. this.skeletons.forEach(function (o) {
  24910. _this.scene.addSkeleton(o);
  24911. });
  24912. this.particleSystems.forEach(function (o) {
  24913. _this.scene.addParticleSystem(o);
  24914. });
  24915. this.animations.forEach(function (o) {
  24916. _this.scene.addAnimation(o);
  24917. });
  24918. this.multiMaterials.forEach(function (o) {
  24919. _this.scene.addMultiMaterial(o);
  24920. });
  24921. this.materials.forEach(function (o) {
  24922. _this.scene.addMaterial(o);
  24923. });
  24924. this.morphTargetManagers.forEach(function (o) {
  24925. _this.scene.addMorphTargetManager(o);
  24926. });
  24927. this.geometries.forEach(function (o) {
  24928. _this.scene.addGeometry(o);
  24929. });
  24930. this.transformNodes.forEach(function (o) {
  24931. _this.scene.addTransformNode(o);
  24932. });
  24933. this.lensFlareSystems.forEach(function (o) {
  24934. _this.scene.addLensFlareSystem(o);
  24935. });
  24936. this.actionManagers.forEach(function (o) {
  24937. _this.scene.addActionManager(o);
  24938. });
  24939. this.sounds.forEach(function (o) {
  24940. o.play();
  24941. o.autoplay = true;
  24942. _this.scene.mainSoundTrack.AddSound(o);
  24943. });
  24944. };
  24945. /**
  24946. * Removes all the assets in the container from the scene
  24947. */
  24948. AssetContainer.prototype.removeAllFromScene = function () {
  24949. var _this = this;
  24950. this.cameras.forEach(function (o) {
  24951. _this.scene.removeCamera(o);
  24952. });
  24953. this.lights.forEach(function (o) {
  24954. _this.scene.removeLight(o);
  24955. });
  24956. this.meshes.forEach(function (o) {
  24957. _this.scene.removeMesh(o);
  24958. });
  24959. this.skeletons.forEach(function (o) {
  24960. _this.scene.removeSkeleton(o);
  24961. });
  24962. this.particleSystems.forEach(function (o) {
  24963. _this.scene.removeParticleSystem(o);
  24964. });
  24965. this.animations.forEach(function (o) {
  24966. _this.scene.removeAnimation(o);
  24967. });
  24968. this.multiMaterials.forEach(function (o) {
  24969. _this.scene.removeMultiMaterial(o);
  24970. });
  24971. this.materials.forEach(function (o) {
  24972. _this.scene.removeMaterial(o);
  24973. });
  24974. this.morphTargetManagers.forEach(function (o) {
  24975. _this.scene.removeMorphTargetManager(o);
  24976. });
  24977. this.geometries.forEach(function (o) {
  24978. _this.scene.removeGeometry(o);
  24979. });
  24980. this.transformNodes.forEach(function (o) {
  24981. _this.scene.removeTransformNode(o);
  24982. });
  24983. this.lensFlareSystems.forEach(function (o) {
  24984. _this.scene.removeLensFlareSystem(o);
  24985. });
  24986. this.actionManagers.forEach(function (o) {
  24987. _this.scene.removeActionManager(o);
  24988. });
  24989. this.sounds.forEach(function (o) {
  24990. o.stop();
  24991. o.autoplay = false;
  24992. _this.scene.mainSoundTrack.RemoveSound(o);
  24993. });
  24994. };
  24995. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  24996. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  24997. var asset = sourceAssets_1[_i];
  24998. var move = true;
  24999. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25000. var keepAsset = keepAssets_1[_a];
  25001. if (asset === keepAsset) {
  25002. move = false;
  25003. break;
  25004. }
  25005. }
  25006. if (move) {
  25007. targetAssets.push(asset);
  25008. }
  25009. }
  25010. };
  25011. /**
  25012. * Removes all the assets contained in the scene and adds them to the container.
  25013. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25014. */
  25015. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25016. if (keepAssets === undefined) {
  25017. keepAssets = new KeepAssets();
  25018. }
  25019. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25020. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25021. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25022. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25023. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25024. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25025. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25026. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25027. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25028. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25029. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25030. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25031. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25032. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25033. this.removeAllFromScene();
  25034. };
  25035. return AssetContainer;
  25036. }());
  25037. BABYLON.AssetContainer = AssetContainer;
  25038. })(BABYLON || (BABYLON = {}));
  25039. //# sourceMappingURL=babylon.assetContainer.js.map
  25040. var BABYLON;
  25041. (function (BABYLON) {
  25042. var Buffer = /** @class */ (function () {
  25043. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25044. if (instanced === void 0) { instanced = false; }
  25045. if (engine instanceof BABYLON.Mesh) {
  25046. this._engine = engine.getScene().getEngine();
  25047. }
  25048. else {
  25049. this._engine = engine;
  25050. }
  25051. this._updatable = updatable;
  25052. this._data = data;
  25053. this._strideSize = stride;
  25054. if (!postponeInternalCreation) {
  25055. this.create();
  25056. }
  25057. this._instanced = instanced;
  25058. this._instanceDivisor = instanced ? 1 : 0;
  25059. }
  25060. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  25061. // a lot of these parameters are ignored as they are overriden by the buffer
  25062. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  25063. };
  25064. // Properties
  25065. Buffer.prototype.isUpdatable = function () {
  25066. return this._updatable;
  25067. };
  25068. Buffer.prototype.getData = function () {
  25069. return this._data;
  25070. };
  25071. Buffer.prototype.getBuffer = function () {
  25072. return this._buffer;
  25073. };
  25074. Buffer.prototype.getStrideSize = function () {
  25075. return this._strideSize;
  25076. };
  25077. Buffer.prototype.getIsInstanced = function () {
  25078. return this._instanced;
  25079. };
  25080. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  25081. get: function () {
  25082. return this._instanceDivisor;
  25083. },
  25084. set: function (value) {
  25085. this._instanceDivisor = value;
  25086. if (value == 0) {
  25087. this._instanced = false;
  25088. }
  25089. else {
  25090. this._instanced = true;
  25091. }
  25092. },
  25093. enumerable: true,
  25094. configurable: true
  25095. });
  25096. // Methods
  25097. Buffer.prototype.create = function (data) {
  25098. if (data === void 0) { data = null; }
  25099. if (!data && this._buffer) {
  25100. return; // nothing to do
  25101. }
  25102. data = data || this._data;
  25103. if (!data) {
  25104. return;
  25105. }
  25106. if (!this._buffer) {
  25107. if (this._updatable) {
  25108. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25109. this._data = data;
  25110. }
  25111. else {
  25112. this._buffer = this._engine.createVertexBuffer(data);
  25113. }
  25114. }
  25115. else if (this._updatable) {
  25116. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25117. this._data = data;
  25118. }
  25119. };
  25120. Buffer.prototype._rebuild = function () {
  25121. this._buffer = null;
  25122. this.create(this._data);
  25123. };
  25124. Buffer.prototype.update = function (data) {
  25125. this.create(data);
  25126. };
  25127. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25128. if (!this._buffer) {
  25129. return;
  25130. }
  25131. if (this._updatable) {
  25132. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25133. this._data = null;
  25134. }
  25135. };
  25136. Buffer.prototype.dispose = function () {
  25137. if (!this._buffer) {
  25138. return;
  25139. }
  25140. if (this._engine._releaseBuffer(this._buffer)) {
  25141. this._buffer = null;
  25142. }
  25143. };
  25144. return Buffer;
  25145. }());
  25146. BABYLON.Buffer = Buffer;
  25147. })(BABYLON || (BABYLON = {}));
  25148. //# sourceMappingURL=babylon.buffer.js.map
  25149. var BABYLON;
  25150. (function (BABYLON) {
  25151. var VertexBuffer = /** @class */ (function () {
  25152. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25153. if (!stride) {
  25154. stride = VertexBuffer.DeduceStride(kind);
  25155. }
  25156. if (data instanceof BABYLON.Buffer) {
  25157. if (!stride) {
  25158. stride = data.getStrideSize();
  25159. }
  25160. this._buffer = data;
  25161. this._ownsBuffer = false;
  25162. }
  25163. else {
  25164. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25165. this._ownsBuffer = true;
  25166. }
  25167. this._stride = stride;
  25168. this._offset = offset ? offset : 0;
  25169. this._size = size ? size : stride;
  25170. this._kind = kind;
  25171. }
  25172. VertexBuffer.prototype._rebuild = function () {
  25173. if (!this._buffer) {
  25174. return;
  25175. }
  25176. this._buffer._rebuild();
  25177. };
  25178. /**
  25179. * Returns the kind of the VertexBuffer (string).
  25180. */
  25181. VertexBuffer.prototype.getKind = function () {
  25182. return this._kind;
  25183. };
  25184. // Properties
  25185. /**
  25186. * Boolean : is the VertexBuffer updatable ?
  25187. */
  25188. VertexBuffer.prototype.isUpdatable = function () {
  25189. return this._buffer.isUpdatable();
  25190. };
  25191. /**
  25192. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25193. */
  25194. VertexBuffer.prototype.getData = function () {
  25195. return this._buffer.getData();
  25196. };
  25197. /**
  25198. * Returns the WebGLBuffer associated to the VertexBuffer.
  25199. */
  25200. VertexBuffer.prototype.getBuffer = function () {
  25201. return this._buffer.getBuffer();
  25202. };
  25203. /**
  25204. * Returns the stride of the VertexBuffer (integer).
  25205. */
  25206. VertexBuffer.prototype.getStrideSize = function () {
  25207. return this._stride;
  25208. };
  25209. /**
  25210. * Returns the offset (integer).
  25211. */
  25212. VertexBuffer.prototype.getOffset = function () {
  25213. return this._offset;
  25214. };
  25215. /**
  25216. * Returns the VertexBuffer total size (integer).
  25217. */
  25218. VertexBuffer.prototype.getSize = function () {
  25219. return this._size;
  25220. };
  25221. /**
  25222. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25223. */
  25224. VertexBuffer.prototype.getIsInstanced = function () {
  25225. return this._buffer.getIsInstanced();
  25226. };
  25227. /**
  25228. * Returns the instancing divisor, zero for non-instanced (integer).
  25229. */
  25230. VertexBuffer.prototype.getInstanceDivisor = function () {
  25231. return this._buffer.instanceDivisor;
  25232. };
  25233. // Methods
  25234. /**
  25235. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25236. * Returns the created WebGLBuffer.
  25237. */
  25238. VertexBuffer.prototype.create = function (data) {
  25239. return this._buffer.create(data);
  25240. };
  25241. /**
  25242. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25243. * This function will create a new buffer if the current one is not updatable
  25244. * Returns the updated WebGLBuffer.
  25245. */
  25246. VertexBuffer.prototype.update = function (data) {
  25247. return this._buffer.update(data);
  25248. };
  25249. /**
  25250. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25251. * Returns the directly updated WebGLBuffer.
  25252. */
  25253. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25254. return this._buffer.updateDirectly(data, offset);
  25255. };
  25256. /**
  25257. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25258. */
  25259. VertexBuffer.prototype.dispose = function () {
  25260. if (this._ownsBuffer) {
  25261. this._buffer.dispose();
  25262. }
  25263. };
  25264. Object.defineProperty(VertexBuffer, "PositionKind", {
  25265. get: function () {
  25266. return VertexBuffer._PositionKind;
  25267. },
  25268. enumerable: true,
  25269. configurable: true
  25270. });
  25271. Object.defineProperty(VertexBuffer, "NormalKind", {
  25272. get: function () {
  25273. return VertexBuffer._NormalKind;
  25274. },
  25275. enumerable: true,
  25276. configurable: true
  25277. });
  25278. Object.defineProperty(VertexBuffer, "TangentKind", {
  25279. get: function () {
  25280. return VertexBuffer._TangentKind;
  25281. },
  25282. enumerable: true,
  25283. configurable: true
  25284. });
  25285. Object.defineProperty(VertexBuffer, "UVKind", {
  25286. get: function () {
  25287. return VertexBuffer._UVKind;
  25288. },
  25289. enumerable: true,
  25290. configurable: true
  25291. });
  25292. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25293. get: function () {
  25294. return VertexBuffer._UV2Kind;
  25295. },
  25296. enumerable: true,
  25297. configurable: true
  25298. });
  25299. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25300. get: function () {
  25301. return VertexBuffer._UV3Kind;
  25302. },
  25303. enumerable: true,
  25304. configurable: true
  25305. });
  25306. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25307. get: function () {
  25308. return VertexBuffer._UV4Kind;
  25309. },
  25310. enumerable: true,
  25311. configurable: true
  25312. });
  25313. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25314. get: function () {
  25315. return VertexBuffer._UV5Kind;
  25316. },
  25317. enumerable: true,
  25318. configurable: true
  25319. });
  25320. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25321. get: function () {
  25322. return VertexBuffer._UV6Kind;
  25323. },
  25324. enumerable: true,
  25325. configurable: true
  25326. });
  25327. Object.defineProperty(VertexBuffer, "ColorKind", {
  25328. get: function () {
  25329. return VertexBuffer._ColorKind;
  25330. },
  25331. enumerable: true,
  25332. configurable: true
  25333. });
  25334. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25335. get: function () {
  25336. return VertexBuffer._MatricesIndicesKind;
  25337. },
  25338. enumerable: true,
  25339. configurable: true
  25340. });
  25341. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25342. get: function () {
  25343. return VertexBuffer._MatricesWeightsKind;
  25344. },
  25345. enumerable: true,
  25346. configurable: true
  25347. });
  25348. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25349. get: function () {
  25350. return VertexBuffer._MatricesIndicesExtraKind;
  25351. },
  25352. enumerable: true,
  25353. configurable: true
  25354. });
  25355. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25356. get: function () {
  25357. return VertexBuffer._MatricesWeightsExtraKind;
  25358. },
  25359. enumerable: true,
  25360. configurable: true
  25361. });
  25362. /**
  25363. * Deduces the stride given a kind.
  25364. * @param kind The kind string to deduce
  25365. * @returns The deduced stride
  25366. */
  25367. VertexBuffer.DeduceStride = function (kind) {
  25368. switch (kind) {
  25369. case VertexBuffer.PositionKind:
  25370. return 3;
  25371. case VertexBuffer.NormalKind:
  25372. return 3;
  25373. case VertexBuffer.UVKind:
  25374. case VertexBuffer.UV2Kind:
  25375. case VertexBuffer.UV3Kind:
  25376. case VertexBuffer.UV4Kind:
  25377. case VertexBuffer.UV5Kind:
  25378. case VertexBuffer.UV6Kind:
  25379. return 2;
  25380. case VertexBuffer.TangentKind:
  25381. case VertexBuffer.ColorKind:
  25382. return 4;
  25383. case VertexBuffer.MatricesIndicesKind:
  25384. case VertexBuffer.MatricesIndicesExtraKind:
  25385. return 4;
  25386. case VertexBuffer.MatricesWeightsKind:
  25387. case VertexBuffer.MatricesWeightsExtraKind:
  25388. return 4;
  25389. default:
  25390. throw new Error("Invalid kind '" + kind + "'");
  25391. }
  25392. };
  25393. // Enums
  25394. VertexBuffer._PositionKind = "position";
  25395. VertexBuffer._NormalKind = "normal";
  25396. VertexBuffer._TangentKind = "tangent";
  25397. VertexBuffer._UVKind = "uv";
  25398. VertexBuffer._UV2Kind = "uv2";
  25399. VertexBuffer._UV3Kind = "uv3";
  25400. VertexBuffer._UV4Kind = "uv4";
  25401. VertexBuffer._UV5Kind = "uv5";
  25402. VertexBuffer._UV6Kind = "uv6";
  25403. VertexBuffer._ColorKind = "color";
  25404. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25405. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25406. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25407. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25408. return VertexBuffer;
  25409. }());
  25410. BABYLON.VertexBuffer = VertexBuffer;
  25411. })(BABYLON || (BABYLON = {}));
  25412. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25413. var BABYLON;
  25414. (function (BABYLON) {
  25415. /**
  25416. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25417. */
  25418. var DummyInternalTextureTracker = /** @class */ (function () {
  25419. function DummyInternalTextureTracker() {
  25420. /**
  25421. * Gets or set the previous tracker in the list
  25422. */
  25423. this.previous = null;
  25424. /**
  25425. * Gets or set the next tracker in the list
  25426. */
  25427. this.next = null;
  25428. }
  25429. return DummyInternalTextureTracker;
  25430. }());
  25431. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25432. })(BABYLON || (BABYLON = {}));
  25433. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25434. var BABYLON;
  25435. (function (BABYLON) {
  25436. /**
  25437. * Class used to store data associated with WebGL texture data for the engine
  25438. * This class should not be used directly
  25439. */
  25440. var InternalTexture = /** @class */ (function () {
  25441. /**
  25442. * Creates a new InternalTexture
  25443. * @param engine defines the engine to use
  25444. * @param dataSource defines the type of data that will be used
  25445. */
  25446. function InternalTexture(engine, dataSource) {
  25447. /**
  25448. * Observable called when the texture is loaded
  25449. */
  25450. this.onLoadedObservable = new BABYLON.Observable();
  25451. /**
  25452. * Gets or set the previous tracker in the list
  25453. */
  25454. this.previous = null;
  25455. /**
  25456. * Gets or set the next tracker in the list
  25457. */
  25458. this.next = null;
  25459. // Private
  25460. /** @ignore */
  25461. this._initialSlot = -1;
  25462. /** @ignore */
  25463. this._designatedSlot = -1;
  25464. /** @ignore */
  25465. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25466. /** @ignore */
  25467. this._references = 1;
  25468. this._engine = engine;
  25469. this._dataSource = dataSource;
  25470. this._webGLTexture = engine._createTexture();
  25471. }
  25472. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25473. /**
  25474. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25475. */
  25476. get: function () {
  25477. return this._dataSource;
  25478. },
  25479. enumerable: true,
  25480. configurable: true
  25481. });
  25482. /**
  25483. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25484. */
  25485. InternalTexture.prototype.incrementReferences = function () {
  25486. this._references++;
  25487. };
  25488. /**
  25489. * Change the size of the texture (not the size of the content)
  25490. * @param width defines the new width
  25491. * @param height defines the new height
  25492. * @param depth defines the new depth (1 by default)
  25493. */
  25494. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25495. if (depth === void 0) { depth = 1; }
  25496. this.width = width;
  25497. this.height = height;
  25498. this.depth = depth;
  25499. this.baseWidth = width;
  25500. this.baseHeight = height;
  25501. this.baseDepth = depth;
  25502. this._size = width * height * depth;
  25503. };
  25504. /** @ignore */
  25505. InternalTexture.prototype._rebuild = function () {
  25506. var _this = this;
  25507. var proxy;
  25508. this.isReady = false;
  25509. this._cachedCoordinatesMode = null;
  25510. this._cachedWrapU = null;
  25511. this._cachedWrapV = null;
  25512. this._cachedAnisotropicFilteringLevel = null;
  25513. switch (this._dataSource) {
  25514. case InternalTexture.DATASOURCE_TEMP:
  25515. return;
  25516. case InternalTexture.DATASOURCE_URL:
  25517. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25518. _this.isReady = true;
  25519. }, null, this._buffer, undefined, this.format);
  25520. proxy._swapAndDie(this);
  25521. return;
  25522. case InternalTexture.DATASOURCE_RAW:
  25523. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25524. proxy._swapAndDie(this);
  25525. this.isReady = true;
  25526. return;
  25527. case InternalTexture.DATASOURCE_RAW3D:
  25528. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25529. proxy._swapAndDie(this);
  25530. this.isReady = true;
  25531. return;
  25532. case InternalTexture.DATASOURCE_DYNAMIC:
  25533. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25534. proxy._swapAndDie(this);
  25535. // The engine will make sure to update content so no need to flag it as isReady = true
  25536. return;
  25537. case InternalTexture.DATASOURCE_RENDERTARGET:
  25538. var options = new BABYLON.RenderTargetCreationOptions();
  25539. options.generateDepthBuffer = this._generateDepthBuffer;
  25540. options.generateMipMaps = this.generateMipMaps;
  25541. options.generateStencilBuffer = this._generateStencilBuffer;
  25542. options.samplingMode = this.samplingMode;
  25543. options.type = this.type;
  25544. if (this.isCube) {
  25545. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25546. }
  25547. else {
  25548. var size = {
  25549. width: this.width,
  25550. height: this.height
  25551. };
  25552. proxy = this._engine.createRenderTargetTexture(size, options);
  25553. }
  25554. proxy._swapAndDie(this);
  25555. this.isReady = true;
  25556. return;
  25557. case InternalTexture.DATASOURCE_CUBE:
  25558. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25559. _this.isReady = true;
  25560. }, null, this.format, this._extension);
  25561. proxy._swapAndDie(this);
  25562. return;
  25563. case InternalTexture.DATASOURCE_CUBERAW:
  25564. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25565. proxy._swapAndDie(this);
  25566. this.isReady = true;
  25567. return;
  25568. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25569. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25570. if (proxy) {
  25571. proxy._swapAndDie(_this);
  25572. }
  25573. _this.isReady = true;
  25574. }, null, this.format, this._extension);
  25575. return;
  25576. }
  25577. };
  25578. InternalTexture.prototype._swapAndDie = function (target) {
  25579. target._webGLTexture = this._webGLTexture;
  25580. if (this._framebuffer) {
  25581. target._framebuffer = this._framebuffer;
  25582. }
  25583. if (this._depthStencilBuffer) {
  25584. target._depthStencilBuffer = this._depthStencilBuffer;
  25585. }
  25586. if (this._lodTextureHigh) {
  25587. if (target._lodTextureHigh) {
  25588. target._lodTextureHigh.dispose();
  25589. }
  25590. target._lodTextureHigh = this._lodTextureHigh;
  25591. }
  25592. if (this._lodTextureMid) {
  25593. if (target._lodTextureMid) {
  25594. target._lodTextureMid.dispose();
  25595. }
  25596. target._lodTextureMid = this._lodTextureMid;
  25597. }
  25598. if (this._lodTextureLow) {
  25599. if (target._lodTextureLow) {
  25600. target._lodTextureLow.dispose();
  25601. }
  25602. target._lodTextureLow = this._lodTextureLow;
  25603. }
  25604. var cache = this._engine.getLoadedTexturesCache();
  25605. var index = cache.indexOf(this);
  25606. if (index !== -1) {
  25607. cache.splice(index, 1);
  25608. }
  25609. };
  25610. /**
  25611. * Dispose the current allocated resources
  25612. */
  25613. InternalTexture.prototype.dispose = function () {
  25614. if (!this._webGLTexture) {
  25615. return;
  25616. }
  25617. this._references--;
  25618. if (this._references === 0) {
  25619. this._engine._releaseTexture(this);
  25620. this._webGLTexture = null;
  25621. this.previous = null;
  25622. this.next = null;
  25623. }
  25624. };
  25625. /**
  25626. * The source of the texture data is unknown
  25627. */
  25628. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25629. /**
  25630. * Texture data comes from an URL
  25631. */
  25632. InternalTexture.DATASOURCE_URL = 1;
  25633. /**
  25634. * Texture data is only used for temporary storage
  25635. */
  25636. InternalTexture.DATASOURCE_TEMP = 2;
  25637. /**
  25638. * Texture data comes from raw data (ArrayBuffer)
  25639. */
  25640. InternalTexture.DATASOURCE_RAW = 3;
  25641. /**
  25642. * Texture content is dynamic (video or dynamic texture)
  25643. */
  25644. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25645. /**
  25646. * Texture content is generated by rendering to it
  25647. */
  25648. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25649. /**
  25650. * Texture content is part of a multi render target process
  25651. */
  25652. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25653. /**
  25654. * Texture data comes from a cube data file
  25655. */
  25656. InternalTexture.DATASOURCE_CUBE = 7;
  25657. /**
  25658. * Texture data comes from a raw cube data
  25659. */
  25660. InternalTexture.DATASOURCE_CUBERAW = 8;
  25661. /**
  25662. * Texture data come from a prefiltered cube data file
  25663. */
  25664. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  25665. /**
  25666. * Texture content is raw 3D data
  25667. */
  25668. InternalTexture.DATASOURCE_RAW3D = 10;
  25669. return InternalTexture;
  25670. }());
  25671. BABYLON.InternalTexture = InternalTexture;
  25672. })(BABYLON || (BABYLON = {}));
  25673. //# sourceMappingURL=babylon.internalTexture.js.map
  25674. var BABYLON;
  25675. (function (BABYLON) {
  25676. var BaseTexture = /** @class */ (function () {
  25677. function BaseTexture(scene) {
  25678. this._hasAlpha = false;
  25679. this.getAlphaFromRGB = false;
  25680. this.level = 1;
  25681. this.coordinatesIndex = 0;
  25682. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25683. /*
  25684. * How a texture is mapped.
  25685. *
  25686. * | Value | Type | Description |
  25687. * | ----- | ----------------------------------- | ----------- |
  25688. * | 0 | EXPLICIT_MODE | |
  25689. * | 1 | SPHERICAL_MODE | |
  25690. * | 2 | PLANAR_MODE | |
  25691. * | 3 | CUBIC_MODE | |
  25692. * | 4 | PROJECTION_MODE | |
  25693. * | 5 | SKYBOX_MODE | |
  25694. * | 6 | INVCUBIC_MODE | |
  25695. * | 7 | EQUIRECTANGULAR_MODE | |
  25696. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  25697. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  25698. */
  25699. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25700. /*
  25701. * | Value | Type | Description |
  25702. * | ----- | ------------------ | ----------- |
  25703. * | 0 | CLAMP_ADDRESSMODE | |
  25704. * | 1 | WRAP_ADDRESSMODE | |
  25705. * | 2 | MIRROR_ADDRESSMODE | |
  25706. */
  25707. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25708. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25709. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25710. this.isCube = false;
  25711. this.is3D = false;
  25712. this.gammaSpace = true;
  25713. this.invertZ = false;
  25714. this.lodLevelInAlpha = false;
  25715. this.lodGenerationOffset = 0.0;
  25716. this.lodGenerationScale = 0.8;
  25717. this.isRenderTarget = false;
  25718. this.animations = new Array();
  25719. /**
  25720. * An event triggered when the texture is disposed.
  25721. * @type {BABYLON.Observable}
  25722. */
  25723. this.onDisposeObservable = new BABYLON.Observable();
  25724. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25725. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25726. if (this._scene) {
  25727. this._scene.textures.push(this);
  25728. }
  25729. this._uid = null;
  25730. }
  25731. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25732. get: function () {
  25733. return this._hasAlpha;
  25734. },
  25735. set: function (value) {
  25736. if (this._hasAlpha === value) {
  25737. return;
  25738. }
  25739. this._hasAlpha = value;
  25740. if (this._scene) {
  25741. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  25742. }
  25743. },
  25744. enumerable: true,
  25745. configurable: true
  25746. });
  25747. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  25748. get: function () {
  25749. return this._coordinatesMode;
  25750. },
  25751. set: function (value) {
  25752. if (this._coordinatesMode === value) {
  25753. return;
  25754. }
  25755. this._coordinatesMode = value;
  25756. if (this._scene) {
  25757. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25758. }
  25759. },
  25760. enumerable: true,
  25761. configurable: true
  25762. });
  25763. Object.defineProperty(BaseTexture.prototype, "uid", {
  25764. get: function () {
  25765. if (!this._uid) {
  25766. this._uid = BABYLON.Tools.RandomId();
  25767. }
  25768. return this._uid;
  25769. },
  25770. enumerable: true,
  25771. configurable: true
  25772. });
  25773. BaseTexture.prototype.toString = function () {
  25774. return this.name;
  25775. };
  25776. BaseTexture.prototype.getClassName = function () {
  25777. return "BaseTexture";
  25778. };
  25779. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  25780. set: function (callback) {
  25781. if (this._onDisposeObserver) {
  25782. this.onDisposeObservable.remove(this._onDisposeObserver);
  25783. }
  25784. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25785. },
  25786. enumerable: true,
  25787. configurable: true
  25788. });
  25789. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  25790. get: function () {
  25791. return true;
  25792. },
  25793. enumerable: true,
  25794. configurable: true
  25795. });
  25796. BaseTexture.prototype.getScene = function () {
  25797. return this._scene;
  25798. };
  25799. BaseTexture.prototype.getTextureMatrix = function () {
  25800. return BABYLON.Matrix.IdentityReadOnly;
  25801. };
  25802. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  25803. return BABYLON.Matrix.IdentityReadOnly;
  25804. };
  25805. BaseTexture.prototype.getInternalTexture = function () {
  25806. return this._texture;
  25807. };
  25808. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  25809. return !this.isBlocking || this.isReady();
  25810. };
  25811. BaseTexture.prototype.isReady = function () {
  25812. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25813. this.delayLoad();
  25814. return false;
  25815. }
  25816. if (this._texture) {
  25817. return this._texture.isReady;
  25818. }
  25819. return false;
  25820. };
  25821. BaseTexture.prototype.getSize = function () {
  25822. if (this._texture && this._texture.width) {
  25823. return new BABYLON.Size(this._texture.width, this._texture.height);
  25824. }
  25825. if (this._texture && this._texture._size) {
  25826. return new BABYLON.Size(this._texture._size, this._texture._size);
  25827. }
  25828. return BABYLON.Size.Zero();
  25829. };
  25830. BaseTexture.prototype.getBaseSize = function () {
  25831. if (!this.isReady() || !this._texture)
  25832. return BABYLON.Size.Zero();
  25833. if (this._texture._size) {
  25834. return new BABYLON.Size(this._texture._size, this._texture._size);
  25835. }
  25836. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25837. };
  25838. BaseTexture.prototype.scale = function (ratio) {
  25839. };
  25840. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25841. get: function () {
  25842. return false;
  25843. },
  25844. enumerable: true,
  25845. configurable: true
  25846. });
  25847. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25848. if (!this._scene) {
  25849. return null;
  25850. }
  25851. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25852. for (var index = 0; index < texturesCache.length; index++) {
  25853. var texturesCacheEntry = texturesCache[index];
  25854. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25855. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25856. texturesCacheEntry.incrementReferences();
  25857. return texturesCacheEntry;
  25858. }
  25859. }
  25860. }
  25861. return null;
  25862. };
  25863. BaseTexture.prototype._rebuild = function () {
  25864. };
  25865. BaseTexture.prototype.delayLoad = function () {
  25866. };
  25867. BaseTexture.prototype.clone = function () {
  25868. return null;
  25869. };
  25870. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25871. get: function () {
  25872. if (!this._texture) {
  25873. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25874. }
  25875. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25876. },
  25877. enumerable: true,
  25878. configurable: true
  25879. });
  25880. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25881. get: function () {
  25882. if (!this._texture) {
  25883. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25884. }
  25885. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25886. },
  25887. enumerable: true,
  25888. configurable: true
  25889. });
  25890. BaseTexture.prototype.readPixels = function (faceIndex) {
  25891. if (faceIndex === void 0) { faceIndex = 0; }
  25892. if (!this._texture) {
  25893. return null;
  25894. }
  25895. var size = this.getSize();
  25896. var scene = this.getScene();
  25897. if (!scene) {
  25898. return null;
  25899. }
  25900. var engine = scene.getEngine();
  25901. if (this._texture.isCube) {
  25902. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  25903. }
  25904. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  25905. };
  25906. BaseTexture.prototype.releaseInternalTexture = function () {
  25907. if (this._texture) {
  25908. this._texture.dispose();
  25909. this._texture = null;
  25910. }
  25911. };
  25912. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  25913. get: function () {
  25914. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  25915. return null;
  25916. }
  25917. if (!this._texture._sphericalPolynomial) {
  25918. this._texture._sphericalPolynomial =
  25919. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  25920. }
  25921. return this._texture._sphericalPolynomial;
  25922. },
  25923. set: function (value) {
  25924. if (this._texture) {
  25925. this._texture._sphericalPolynomial = value;
  25926. }
  25927. },
  25928. enumerable: true,
  25929. configurable: true
  25930. });
  25931. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  25932. get: function () {
  25933. if (this._texture) {
  25934. return this._texture._lodTextureHigh;
  25935. }
  25936. return null;
  25937. },
  25938. enumerable: true,
  25939. configurable: true
  25940. });
  25941. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  25942. get: function () {
  25943. if (this._texture) {
  25944. return this._texture._lodTextureMid;
  25945. }
  25946. return null;
  25947. },
  25948. enumerable: true,
  25949. configurable: true
  25950. });
  25951. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  25952. get: function () {
  25953. if (this._texture) {
  25954. return this._texture._lodTextureLow;
  25955. }
  25956. return null;
  25957. },
  25958. enumerable: true,
  25959. configurable: true
  25960. });
  25961. BaseTexture.prototype.dispose = function () {
  25962. if (!this._scene) {
  25963. return;
  25964. }
  25965. // Animations
  25966. this._scene.stopAnimation(this);
  25967. // Remove from scene
  25968. this._scene._removePendingData(this);
  25969. var index = this._scene.textures.indexOf(this);
  25970. if (index >= 0) {
  25971. this._scene.textures.splice(index, 1);
  25972. }
  25973. if (this._texture === undefined) {
  25974. return;
  25975. }
  25976. // Release
  25977. this.releaseInternalTexture();
  25978. // Callback
  25979. this.onDisposeObservable.notifyObservers(this);
  25980. this.onDisposeObservable.clear();
  25981. };
  25982. BaseTexture.prototype.serialize = function () {
  25983. if (!this.name) {
  25984. return null;
  25985. }
  25986. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  25987. // Animations
  25988. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25989. return serializationObject;
  25990. };
  25991. BaseTexture.WhenAllReady = function (textures, callback) {
  25992. var numRemaining = textures.length;
  25993. if (numRemaining === 0) {
  25994. callback();
  25995. return;
  25996. }
  25997. var _loop_1 = function () {
  25998. texture = textures[i];
  25999. if (texture.isReady()) {
  26000. if (--numRemaining === 0) {
  26001. callback();
  26002. }
  26003. }
  26004. else {
  26005. onLoadObservable = texture.onLoadObservable;
  26006. var onLoadCallback_1 = function () {
  26007. onLoadObservable.removeCallback(onLoadCallback_1);
  26008. if (--numRemaining === 0) {
  26009. callback();
  26010. }
  26011. };
  26012. onLoadObservable.add(onLoadCallback_1);
  26013. }
  26014. };
  26015. var texture, onLoadObservable;
  26016. for (var i = 0; i < textures.length; i++) {
  26017. _loop_1();
  26018. }
  26019. };
  26020. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26021. __decorate([
  26022. BABYLON.serialize()
  26023. ], BaseTexture.prototype, "name", void 0);
  26024. __decorate([
  26025. BABYLON.serialize("hasAlpha")
  26026. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26027. __decorate([
  26028. BABYLON.serialize()
  26029. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26030. __decorate([
  26031. BABYLON.serialize()
  26032. ], BaseTexture.prototype, "level", void 0);
  26033. __decorate([
  26034. BABYLON.serialize()
  26035. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26036. __decorate([
  26037. BABYLON.serialize("coordinatesMode")
  26038. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26039. __decorate([
  26040. BABYLON.serialize()
  26041. ], BaseTexture.prototype, "wrapU", void 0);
  26042. __decorate([
  26043. BABYLON.serialize()
  26044. ], BaseTexture.prototype, "wrapV", void 0);
  26045. __decorate([
  26046. BABYLON.serialize()
  26047. ], BaseTexture.prototype, "wrapR", void 0);
  26048. __decorate([
  26049. BABYLON.serialize()
  26050. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26051. __decorate([
  26052. BABYLON.serialize()
  26053. ], BaseTexture.prototype, "isCube", void 0);
  26054. __decorate([
  26055. BABYLON.serialize()
  26056. ], BaseTexture.prototype, "is3D", void 0);
  26057. __decorate([
  26058. BABYLON.serialize()
  26059. ], BaseTexture.prototype, "gammaSpace", void 0);
  26060. __decorate([
  26061. BABYLON.serialize()
  26062. ], BaseTexture.prototype, "invertZ", void 0);
  26063. __decorate([
  26064. BABYLON.serialize()
  26065. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26066. __decorate([
  26067. BABYLON.serialize()
  26068. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26069. __decorate([
  26070. BABYLON.serialize()
  26071. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26072. __decorate([
  26073. BABYLON.serialize()
  26074. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26075. return BaseTexture;
  26076. }());
  26077. BABYLON.BaseTexture = BaseTexture;
  26078. })(BABYLON || (BABYLON = {}));
  26079. //# sourceMappingURL=babylon.baseTexture.js.map
  26080. var BABYLON;
  26081. (function (BABYLON) {
  26082. var Texture = /** @class */ (function (_super) {
  26083. __extends(Texture, _super);
  26084. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26085. if (noMipmap === void 0) { noMipmap = false; }
  26086. if (invertY === void 0) { invertY = true; }
  26087. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26088. if (onLoad === void 0) { onLoad = null; }
  26089. if (onError === void 0) { onError = null; }
  26090. if (buffer === void 0) { buffer = null; }
  26091. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26092. var _this = _super.call(this, scene) || this;
  26093. _this.uOffset = 0;
  26094. _this.vOffset = 0;
  26095. _this.uScale = 1.0;
  26096. _this.vScale = 1.0;
  26097. _this.uAng = 0;
  26098. _this.vAng = 0;
  26099. _this.wAng = 0;
  26100. _this._isBlocking = true;
  26101. _this.name = url || "";
  26102. _this.url = url;
  26103. _this._noMipmap = noMipmap;
  26104. _this._invertY = invertY;
  26105. _this._samplingMode = samplingMode;
  26106. _this._buffer = buffer;
  26107. _this._deleteBuffer = deleteBuffer;
  26108. if (format) {
  26109. _this._format = format;
  26110. }
  26111. scene = _this.getScene();
  26112. if (!scene) {
  26113. return _this;
  26114. }
  26115. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26116. var load = function () {
  26117. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26118. _this.onLoadObservable.notifyObservers(_this);
  26119. }
  26120. if (onLoad) {
  26121. onLoad();
  26122. }
  26123. if (!_this.isBlocking && scene) {
  26124. scene.resetCachedMaterial();
  26125. }
  26126. };
  26127. if (!_this.url) {
  26128. _this._delayedOnLoad = load;
  26129. _this._delayedOnError = onError;
  26130. return _this;
  26131. }
  26132. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26133. if (!_this._texture) {
  26134. if (!scene.useDelayedTextureLoading) {
  26135. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26136. if (deleteBuffer) {
  26137. delete _this._buffer;
  26138. }
  26139. }
  26140. else {
  26141. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26142. _this._delayedOnLoad = load;
  26143. _this._delayedOnError = onError;
  26144. }
  26145. }
  26146. else {
  26147. if (_this._texture.isReady) {
  26148. BABYLON.Tools.SetImmediate(function () { return load(); });
  26149. }
  26150. else {
  26151. _this._texture.onLoadedObservable.add(load);
  26152. }
  26153. }
  26154. return _this;
  26155. }
  26156. Object.defineProperty(Texture.prototype, "noMipmap", {
  26157. get: function () {
  26158. return this._noMipmap;
  26159. },
  26160. enumerable: true,
  26161. configurable: true
  26162. });
  26163. Object.defineProperty(Texture.prototype, "isBlocking", {
  26164. get: function () {
  26165. return this._isBlocking;
  26166. },
  26167. set: function (value) {
  26168. this._isBlocking = value;
  26169. },
  26170. enumerable: true,
  26171. configurable: true
  26172. });
  26173. Object.defineProperty(Texture.prototype, "samplingMode", {
  26174. get: function () {
  26175. return this._samplingMode;
  26176. },
  26177. enumerable: true,
  26178. configurable: true
  26179. });
  26180. Texture.prototype.updateURL = function (url) {
  26181. this.url = url;
  26182. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26183. this.delayLoad();
  26184. };
  26185. Texture.prototype.delayLoad = function () {
  26186. var _this = this;
  26187. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26188. return;
  26189. }
  26190. var scene = this.getScene();
  26191. if (!scene) {
  26192. return;
  26193. }
  26194. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26195. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26196. if (!this._texture) {
  26197. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26198. if (this._deleteBuffer) {
  26199. delete this._buffer;
  26200. }
  26201. }
  26202. else {
  26203. if (this._texture.isReady) {
  26204. BABYLON.Tools.SetImmediate(function () {
  26205. if (!_this._delayedOnLoad) {
  26206. return;
  26207. }
  26208. _this._delayedOnLoad();
  26209. });
  26210. }
  26211. else {
  26212. if (this._delayedOnLoad) {
  26213. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26214. }
  26215. }
  26216. }
  26217. };
  26218. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26219. if (!this._texture) {
  26220. return;
  26221. }
  26222. var scene = this.getScene();
  26223. if (!scene) {
  26224. return;
  26225. }
  26226. this._samplingMode = samplingMode;
  26227. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26228. };
  26229. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26230. x *= this.uScale;
  26231. y *= this.vScale;
  26232. x -= 0.5 * this.uScale;
  26233. y -= 0.5 * this.vScale;
  26234. z -= 0.5;
  26235. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26236. t.x += 0.5 * this.uScale + this.uOffset;
  26237. t.y += 0.5 * this.vScale + this.vOffset;
  26238. t.z += 0.5;
  26239. };
  26240. Texture.prototype.getTextureMatrix = function () {
  26241. var _this = this;
  26242. if (this.uOffset === this._cachedUOffset &&
  26243. this.vOffset === this._cachedVOffset &&
  26244. this.uScale === this._cachedUScale &&
  26245. this.vScale === this._cachedVScale &&
  26246. this.uAng === this._cachedUAng &&
  26247. this.vAng === this._cachedVAng &&
  26248. this.wAng === this._cachedWAng) {
  26249. return this._cachedTextureMatrix;
  26250. }
  26251. this._cachedUOffset = this.uOffset;
  26252. this._cachedVOffset = this.vOffset;
  26253. this._cachedUScale = this.uScale;
  26254. this._cachedVScale = this.vScale;
  26255. this._cachedUAng = this.uAng;
  26256. this._cachedVAng = this.vAng;
  26257. this._cachedWAng = this.wAng;
  26258. if (!this._cachedTextureMatrix) {
  26259. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26260. this._rowGenerationMatrix = new BABYLON.Matrix();
  26261. this._t0 = BABYLON.Vector3.Zero();
  26262. this._t1 = BABYLON.Vector3.Zero();
  26263. this._t2 = BABYLON.Vector3.Zero();
  26264. }
  26265. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26266. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26267. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26268. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26269. this._t1.subtractInPlace(this._t0);
  26270. this._t2.subtractInPlace(this._t0);
  26271. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26272. this._cachedTextureMatrix.m[0] = this._t1.x;
  26273. this._cachedTextureMatrix.m[1] = this._t1.y;
  26274. this._cachedTextureMatrix.m[2] = this._t1.z;
  26275. this._cachedTextureMatrix.m[4] = this._t2.x;
  26276. this._cachedTextureMatrix.m[5] = this._t2.y;
  26277. this._cachedTextureMatrix.m[6] = this._t2.z;
  26278. this._cachedTextureMatrix.m[8] = this._t0.x;
  26279. this._cachedTextureMatrix.m[9] = this._t0.y;
  26280. this._cachedTextureMatrix.m[10] = this._t0.z;
  26281. var scene = this.getScene();
  26282. if (!scene) {
  26283. return this._cachedTextureMatrix;
  26284. }
  26285. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26286. return mat.hasTexture(_this);
  26287. });
  26288. return this._cachedTextureMatrix;
  26289. };
  26290. Texture.prototype.getReflectionTextureMatrix = function () {
  26291. var _this = this;
  26292. var scene = this.getScene();
  26293. if (!scene) {
  26294. return this._cachedTextureMatrix;
  26295. }
  26296. if (this.uOffset === this._cachedUOffset &&
  26297. this.vOffset === this._cachedVOffset &&
  26298. this.uScale === this._cachedUScale &&
  26299. this.vScale === this._cachedVScale &&
  26300. this.coordinatesMode === this._cachedCoordinatesMode) {
  26301. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26302. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26303. return this._cachedTextureMatrix;
  26304. }
  26305. }
  26306. else {
  26307. return this._cachedTextureMatrix;
  26308. }
  26309. }
  26310. if (!this._cachedTextureMatrix) {
  26311. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26312. }
  26313. if (!this._projectionModeMatrix) {
  26314. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26315. }
  26316. this._cachedUOffset = this.uOffset;
  26317. this._cachedVOffset = this.vOffset;
  26318. this._cachedUScale = this.uScale;
  26319. this._cachedVScale = this.vScale;
  26320. this._cachedCoordinatesMode = this.coordinatesMode;
  26321. switch (this.coordinatesMode) {
  26322. case Texture.PLANAR_MODE:
  26323. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26324. this._cachedTextureMatrix[0] = this.uScale;
  26325. this._cachedTextureMatrix[5] = this.vScale;
  26326. this._cachedTextureMatrix[12] = this.uOffset;
  26327. this._cachedTextureMatrix[13] = this.vOffset;
  26328. break;
  26329. case Texture.PROJECTION_MODE:
  26330. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26331. this._projectionModeMatrix.m[0] = 0.5;
  26332. this._projectionModeMatrix.m[5] = -0.5;
  26333. this._projectionModeMatrix.m[10] = 0.0;
  26334. this._projectionModeMatrix.m[12] = 0.5;
  26335. this._projectionModeMatrix.m[13] = 0.5;
  26336. this._projectionModeMatrix.m[14] = 1.0;
  26337. this._projectionModeMatrix.m[15] = 1.0;
  26338. var projectionMatrix = scene.getProjectionMatrix();
  26339. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26340. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26341. break;
  26342. default:
  26343. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26344. break;
  26345. }
  26346. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26347. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26348. });
  26349. return this._cachedTextureMatrix;
  26350. };
  26351. Texture.prototype.clone = function () {
  26352. var _this = this;
  26353. return BABYLON.SerializationHelper.Clone(function () {
  26354. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26355. }, this);
  26356. };
  26357. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26358. get: function () {
  26359. if (!this._onLoadObservable) {
  26360. this._onLoadObservable = new BABYLON.Observable();
  26361. }
  26362. return this._onLoadObservable;
  26363. },
  26364. enumerable: true,
  26365. configurable: true
  26366. });
  26367. Texture.prototype.serialize = function () {
  26368. var serializationObject = _super.prototype.serialize.call(this);
  26369. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26370. serializationObject.base64String = this._buffer;
  26371. serializationObject.name = serializationObject.name.replace("data:", "");
  26372. }
  26373. return serializationObject;
  26374. };
  26375. Texture.prototype.getClassName = function () {
  26376. return "Texture";
  26377. };
  26378. Texture.prototype.dispose = function () {
  26379. _super.prototype.dispose.call(this);
  26380. if (this.onLoadObservable) {
  26381. this.onLoadObservable.clear();
  26382. this._onLoadObservable = null;
  26383. }
  26384. this._delayedOnLoad = null;
  26385. this._delayedOnError = null;
  26386. };
  26387. // Statics
  26388. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26389. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26390. if (onLoad === void 0) { onLoad = null; }
  26391. if (onError === void 0) { onError = null; }
  26392. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26393. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26394. };
  26395. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26396. if (parsedTexture.customType) {
  26397. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26398. // Update Sampling Mode
  26399. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26400. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26401. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26402. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26403. }
  26404. }
  26405. return parsedCustomTexture;
  26406. }
  26407. if (parsedTexture.isCube) {
  26408. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26409. }
  26410. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26411. return null;
  26412. }
  26413. var texture = BABYLON.SerializationHelper.Parse(function () {
  26414. var generateMipMaps = true;
  26415. if (parsedTexture.noMipmap) {
  26416. generateMipMaps = false;
  26417. }
  26418. if (parsedTexture.mirrorPlane) {
  26419. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26420. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26421. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26422. return mirrorTexture;
  26423. }
  26424. else if (parsedTexture.isRenderTarget) {
  26425. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26426. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26427. return renderTargetTexture;
  26428. }
  26429. else {
  26430. var texture;
  26431. if (parsedTexture.base64String) {
  26432. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26433. }
  26434. else {
  26435. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26436. }
  26437. return texture;
  26438. }
  26439. }, parsedTexture, scene);
  26440. // Update Sampling Mode
  26441. if (parsedTexture.samplingMode) {
  26442. var sampling = parsedTexture.samplingMode;
  26443. if (texture._samplingMode !== sampling) {
  26444. texture.updateSamplingMode(sampling);
  26445. }
  26446. }
  26447. // Animations
  26448. if (parsedTexture.animations) {
  26449. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26450. var parsedAnimation = parsedTexture.animations[animationIndex];
  26451. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26452. }
  26453. }
  26454. return texture;
  26455. };
  26456. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26457. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26458. if (noMipmap === void 0) { noMipmap = false; }
  26459. if (invertY === void 0) { invertY = true; }
  26460. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26461. if (onLoad === void 0) { onLoad = null; }
  26462. if (onError === void 0) { onError = null; }
  26463. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26464. if (name.substr(0, 5) !== "data:") {
  26465. name = "data:" + name;
  26466. }
  26467. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26468. };
  26469. // Constants
  26470. Texture.NEAREST_SAMPLINGMODE = 1;
  26471. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26472. Texture.BILINEAR_SAMPLINGMODE = 2;
  26473. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26474. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26475. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26476. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26477. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26478. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26479. Texture.NEAREST_LINEAR = 7;
  26480. Texture.NEAREST_NEAREST = 8;
  26481. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26482. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26483. Texture.LINEAR_LINEAR = 11;
  26484. Texture.LINEAR_NEAREST = 12;
  26485. Texture.EXPLICIT_MODE = 0;
  26486. Texture.SPHERICAL_MODE = 1;
  26487. Texture.PLANAR_MODE = 2;
  26488. Texture.CUBIC_MODE = 3;
  26489. Texture.PROJECTION_MODE = 4;
  26490. Texture.SKYBOX_MODE = 5;
  26491. Texture.INVCUBIC_MODE = 6;
  26492. Texture.EQUIRECTANGULAR_MODE = 7;
  26493. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26494. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26495. Texture.CLAMP_ADDRESSMODE = 0;
  26496. Texture.WRAP_ADDRESSMODE = 1;
  26497. Texture.MIRROR_ADDRESSMODE = 2;
  26498. __decorate([
  26499. BABYLON.serialize()
  26500. ], Texture.prototype, "url", void 0);
  26501. __decorate([
  26502. BABYLON.serialize()
  26503. ], Texture.prototype, "uOffset", void 0);
  26504. __decorate([
  26505. BABYLON.serialize()
  26506. ], Texture.prototype, "vOffset", void 0);
  26507. __decorate([
  26508. BABYLON.serialize()
  26509. ], Texture.prototype, "uScale", void 0);
  26510. __decorate([
  26511. BABYLON.serialize()
  26512. ], Texture.prototype, "vScale", void 0);
  26513. __decorate([
  26514. BABYLON.serialize()
  26515. ], Texture.prototype, "uAng", void 0);
  26516. __decorate([
  26517. BABYLON.serialize()
  26518. ], Texture.prototype, "vAng", void 0);
  26519. __decorate([
  26520. BABYLON.serialize()
  26521. ], Texture.prototype, "wAng", void 0);
  26522. __decorate([
  26523. BABYLON.serialize()
  26524. ], Texture.prototype, "isBlocking", null);
  26525. return Texture;
  26526. }(BABYLON.BaseTexture));
  26527. BABYLON.Texture = Texture;
  26528. })(BABYLON || (BABYLON = {}));
  26529. //# sourceMappingURL=babylon.texture.js.map
  26530. var BABYLON;
  26531. (function (BABYLON) {
  26532. var _InstancesBatch = /** @class */ (function () {
  26533. function _InstancesBatch() {
  26534. this.mustReturn = false;
  26535. this.visibleInstances = new Array();
  26536. this.renderSelf = new Array();
  26537. }
  26538. return _InstancesBatch;
  26539. }());
  26540. BABYLON._InstancesBatch = _InstancesBatch;
  26541. var Mesh = /** @class */ (function (_super) {
  26542. __extends(Mesh, _super);
  26543. /**
  26544. * @constructor
  26545. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26546. * @param {Scene} scene The scene to add this mesh to.
  26547. * @param {Node} parent The parent of this mesh, if it has one
  26548. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26549. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26550. * When false, achieved by calling a clone(), also passing False.
  26551. * This will make creation of children, recursive.
  26552. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26553. */
  26554. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26555. if (scene === void 0) { scene = null; }
  26556. if (parent === void 0) { parent = null; }
  26557. if (source === void 0) { source = null; }
  26558. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26559. var _this = _super.call(this, name, scene) || this;
  26560. // Events
  26561. /**
  26562. * An event triggered before rendering the mesh
  26563. * @type {BABYLON.Observable}
  26564. */
  26565. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26566. /**
  26567. * An event triggered after rendering the mesh
  26568. * @type {BABYLON.Observable}
  26569. */
  26570. _this.onAfterRenderObservable = new BABYLON.Observable();
  26571. /**
  26572. * An event triggered before drawing the mesh
  26573. * @type {BABYLON.Observable}
  26574. */
  26575. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26576. // Members
  26577. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26578. _this.instances = new Array();
  26579. _this._LODLevels = new Array();
  26580. _this._visibleInstances = {};
  26581. _this._renderIdForInstances = new Array();
  26582. _this._batchCache = new _InstancesBatch();
  26583. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26584. // Use by builder only to know what orientation were the mesh build in.
  26585. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26586. _this.overrideMaterialSideOrientation = null;
  26587. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26588. // Will be used to save a source mesh reference, If any
  26589. _this._source = null;
  26590. scene = _this.getScene();
  26591. if (source) {
  26592. // Source mesh
  26593. _this._source = source;
  26594. // Geometry
  26595. if (source._geometry) {
  26596. source._geometry.applyToMesh(_this);
  26597. }
  26598. // Deep copy
  26599. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26600. // Metadata
  26601. if (source.metadata && source.metadata.clone) {
  26602. _this.metadata = source.metadata.clone();
  26603. }
  26604. else {
  26605. _this.metadata = source.metadata;
  26606. }
  26607. // Tags
  26608. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26609. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26610. }
  26611. // Parent
  26612. _this.parent = source.parent;
  26613. // Pivot
  26614. _this.setPivotMatrix(source.getPivotMatrix());
  26615. _this.id = name + "." + source.id;
  26616. // Material
  26617. _this.material = source.material;
  26618. var index;
  26619. if (!doNotCloneChildren) {
  26620. // Children
  26621. var directDescendants = source.getDescendants(true);
  26622. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26623. var child = directDescendants[index_1];
  26624. if (child.clone) {
  26625. child.clone(name + "." + child.name, _this);
  26626. }
  26627. }
  26628. }
  26629. // Physics clone
  26630. var physicsEngine = _this.getScene().getPhysicsEngine();
  26631. if (clonePhysicsImpostor && physicsEngine) {
  26632. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26633. if (impostor) {
  26634. _this.physicsImpostor = impostor.clone(_this);
  26635. }
  26636. }
  26637. // Particles
  26638. for (index = 0; index < scene.particleSystems.length; index++) {
  26639. var system = scene.particleSystems[index];
  26640. if (system.emitter === source) {
  26641. system.clone(system.name, _this);
  26642. }
  26643. }
  26644. _this.computeWorldMatrix(true);
  26645. }
  26646. // Parent
  26647. if (parent !== null) {
  26648. _this.parent = parent;
  26649. }
  26650. return _this;
  26651. }
  26652. Object.defineProperty(Mesh, "FRONTSIDE", {
  26653. /**
  26654. * Mesh side orientation : usually the external or front surface
  26655. */
  26656. get: function () {
  26657. return Mesh._FRONTSIDE;
  26658. },
  26659. enumerable: true,
  26660. configurable: true
  26661. });
  26662. Object.defineProperty(Mesh, "BACKSIDE", {
  26663. /**
  26664. * Mesh side orientation : usually the internal or back surface
  26665. */
  26666. get: function () {
  26667. return Mesh._BACKSIDE;
  26668. },
  26669. enumerable: true,
  26670. configurable: true
  26671. });
  26672. Object.defineProperty(Mesh, "DOUBLESIDE", {
  26673. /**
  26674. * Mesh side orientation : both internal and external or front and back surfaces
  26675. */
  26676. get: function () {
  26677. return Mesh._DOUBLESIDE;
  26678. },
  26679. enumerable: true,
  26680. configurable: true
  26681. });
  26682. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  26683. /**
  26684. * Mesh side orientation : by default, `FRONTSIDE`
  26685. */
  26686. get: function () {
  26687. return Mesh._DEFAULTSIDE;
  26688. },
  26689. enumerable: true,
  26690. configurable: true
  26691. });
  26692. Object.defineProperty(Mesh, "NO_CAP", {
  26693. /**
  26694. * Mesh cap setting : no cap
  26695. */
  26696. get: function () {
  26697. return Mesh._NO_CAP;
  26698. },
  26699. enumerable: true,
  26700. configurable: true
  26701. });
  26702. Object.defineProperty(Mesh, "CAP_START", {
  26703. /**
  26704. * Mesh cap setting : one cap at the beginning of the mesh
  26705. */
  26706. get: function () {
  26707. return Mesh._CAP_START;
  26708. },
  26709. enumerable: true,
  26710. configurable: true
  26711. });
  26712. Object.defineProperty(Mesh, "CAP_END", {
  26713. /**
  26714. * Mesh cap setting : one cap at the end of the mesh
  26715. */
  26716. get: function () {
  26717. return Mesh._CAP_END;
  26718. },
  26719. enumerable: true,
  26720. configurable: true
  26721. });
  26722. Object.defineProperty(Mesh, "CAP_ALL", {
  26723. /**
  26724. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26725. */
  26726. get: function () {
  26727. return Mesh._CAP_ALL;
  26728. },
  26729. enumerable: true,
  26730. configurable: true
  26731. });
  26732. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  26733. set: function (callback) {
  26734. if (this._onBeforeDrawObserver) {
  26735. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  26736. }
  26737. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  26738. },
  26739. enumerable: true,
  26740. configurable: true
  26741. });
  26742. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  26743. get: function () {
  26744. return this._morphTargetManager;
  26745. },
  26746. set: function (value) {
  26747. if (this._morphTargetManager === value) {
  26748. return;
  26749. }
  26750. this._morphTargetManager = value;
  26751. this._syncGeometryWithMorphTargetManager();
  26752. },
  26753. enumerable: true,
  26754. configurable: true
  26755. });
  26756. Object.defineProperty(Mesh.prototype, "source", {
  26757. get: function () {
  26758. return this._source;
  26759. },
  26760. enumerable: true,
  26761. configurable: true
  26762. });
  26763. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  26764. get: function () {
  26765. return this._unIndexed;
  26766. },
  26767. set: function (value) {
  26768. if (this._unIndexed !== value) {
  26769. this._unIndexed = value;
  26770. this._markSubMeshesAsAttributesDirty();
  26771. }
  26772. },
  26773. enumerable: true,
  26774. configurable: true
  26775. });
  26776. // Methods
  26777. /**
  26778. * Returns the string "Mesh".
  26779. */
  26780. Mesh.prototype.getClassName = function () {
  26781. return "Mesh";
  26782. };
  26783. /**
  26784. * Returns a string.
  26785. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26786. */
  26787. Mesh.prototype.toString = function (fullDetails) {
  26788. var ret = _super.prototype.toString.call(this, fullDetails);
  26789. ret += ", n vertices: " + this.getTotalVertices();
  26790. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  26791. if (this.animations) {
  26792. for (var i = 0; i < this.animations.length; i++) {
  26793. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  26794. }
  26795. }
  26796. if (fullDetails) {
  26797. if (this._geometry) {
  26798. var ib = this.getIndices();
  26799. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26800. if (vb && ib) {
  26801. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  26802. }
  26803. }
  26804. else {
  26805. ret += ", flat shading: UNKNOWN";
  26806. }
  26807. }
  26808. return ret;
  26809. };
  26810. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  26811. /**
  26812. * True if the mesh has some Levels Of Details (LOD).
  26813. * Returns a boolean.
  26814. */
  26815. get: function () {
  26816. return this._LODLevels.length > 0;
  26817. },
  26818. enumerable: true,
  26819. configurable: true
  26820. });
  26821. /**
  26822. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  26823. * @returns an array of {BABYLON.MeshLODLevel}
  26824. */
  26825. Mesh.prototype.getLODLevels = function () {
  26826. return this._LODLevels;
  26827. };
  26828. Mesh.prototype._sortLODLevels = function () {
  26829. this._LODLevels.sort(function (a, b) {
  26830. if (a.distance < b.distance) {
  26831. return 1;
  26832. }
  26833. if (a.distance > b.distance) {
  26834. return -1;
  26835. }
  26836. return 0;
  26837. });
  26838. };
  26839. /**
  26840. * Add a mesh as LOD level triggered at the given distance.
  26841. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26842. * @param {number} distance The distance from the center of the object to show this level
  26843. * @param {Mesh} mesh The mesh to be added as LOD level
  26844. * @return {Mesh} This mesh (for chaining)
  26845. */
  26846. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26847. if (mesh && mesh._masterMesh) {
  26848. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26849. return this;
  26850. }
  26851. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26852. this._LODLevels.push(level);
  26853. if (mesh) {
  26854. mesh._masterMesh = this;
  26855. }
  26856. this._sortLODLevels();
  26857. return this;
  26858. };
  26859. /**
  26860. * Returns the LOD level mesh at the passed distance or null if not found.
  26861. * It is related to the method `addLODLevel(distance, mesh)`.
  26862. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26863. * Returns an object Mesh or `null`.
  26864. */
  26865. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26866. for (var index = 0; index < this._LODLevels.length; index++) {
  26867. var level = this._LODLevels[index];
  26868. if (level.distance === distance) {
  26869. return level.mesh;
  26870. }
  26871. }
  26872. return null;
  26873. };
  26874. /**
  26875. * Remove a mesh from the LOD array
  26876. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26877. * @param {Mesh} mesh The mesh to be removed.
  26878. * @return {Mesh} This mesh (for chaining)
  26879. */
  26880. Mesh.prototype.removeLODLevel = function (mesh) {
  26881. for (var index = 0; index < this._LODLevels.length; index++) {
  26882. if (this._LODLevels[index].mesh === mesh) {
  26883. this._LODLevels.splice(index, 1);
  26884. if (mesh) {
  26885. mesh._masterMesh = null;
  26886. }
  26887. }
  26888. }
  26889. this._sortLODLevels();
  26890. return this;
  26891. };
  26892. /**
  26893. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26894. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26895. */
  26896. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  26897. if (!this._LODLevels || this._LODLevels.length === 0) {
  26898. return this;
  26899. }
  26900. var bSphere;
  26901. if (boundingSphere) {
  26902. bSphere = boundingSphere;
  26903. }
  26904. else {
  26905. var boundingInfo = this.getBoundingInfo();
  26906. bSphere = boundingInfo.boundingSphere;
  26907. }
  26908. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  26909. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  26910. if (this.onLODLevelSelection) {
  26911. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  26912. }
  26913. return this;
  26914. }
  26915. for (var index = 0; index < this._LODLevels.length; index++) {
  26916. var level = this._LODLevels[index];
  26917. if (level.distance < distanceToCamera) {
  26918. if (level.mesh) {
  26919. level.mesh._preActivate();
  26920. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  26921. }
  26922. if (this.onLODLevelSelection) {
  26923. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  26924. }
  26925. return level.mesh;
  26926. }
  26927. }
  26928. if (this.onLODLevelSelection) {
  26929. this.onLODLevelSelection(distanceToCamera, this, this);
  26930. }
  26931. return this;
  26932. };
  26933. Object.defineProperty(Mesh.prototype, "geometry", {
  26934. /**
  26935. * Returns the mesh internal Geometry object.
  26936. */
  26937. get: function () {
  26938. return this._geometry;
  26939. },
  26940. enumerable: true,
  26941. configurable: true
  26942. });
  26943. /**
  26944. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  26945. */
  26946. Mesh.prototype.getTotalVertices = function () {
  26947. if (this._geometry === null || this._geometry === undefined) {
  26948. return 0;
  26949. }
  26950. return this._geometry.getTotalVertices();
  26951. };
  26952. /**
  26953. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  26954. * 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.
  26955. * You can force the copy with forceCopy === true
  26956. * Returns null if the mesh has no geometry or no vertex buffer.
  26957. * Possible `kind` values :
  26958. * - BABYLON.VertexBuffer.PositionKind
  26959. * - BABYLON.VertexBuffer.UVKind
  26960. * - BABYLON.VertexBuffer.UV2Kind
  26961. * - BABYLON.VertexBuffer.UV3Kind
  26962. * - BABYLON.VertexBuffer.UV4Kind
  26963. * - BABYLON.VertexBuffer.UV5Kind
  26964. * - BABYLON.VertexBuffer.UV6Kind
  26965. * - BABYLON.VertexBuffer.ColorKind
  26966. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26967. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26968. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26969. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26970. */
  26971. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26972. if (!this._geometry) {
  26973. return null;
  26974. }
  26975. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  26976. };
  26977. /**
  26978. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  26979. * Returns `null` if the mesh has no geometry.
  26980. * Possible `kind` values :
  26981. * - BABYLON.VertexBuffer.PositionKind
  26982. * - BABYLON.VertexBuffer.UVKind
  26983. * - BABYLON.VertexBuffer.UV2Kind
  26984. * - BABYLON.VertexBuffer.UV3Kind
  26985. * - BABYLON.VertexBuffer.UV4Kind
  26986. * - BABYLON.VertexBuffer.UV5Kind
  26987. * - BABYLON.VertexBuffer.UV6Kind
  26988. * - BABYLON.VertexBuffer.ColorKind
  26989. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26990. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26991. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26992. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26993. */
  26994. Mesh.prototype.getVertexBuffer = function (kind) {
  26995. if (!this._geometry) {
  26996. return null;
  26997. }
  26998. return this._geometry.getVertexBuffer(kind);
  26999. };
  27000. /**
  27001. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27002. * Possible `kind` values :
  27003. * - BABYLON.VertexBuffer.PositionKind
  27004. * - BABYLON.VertexBuffer.UVKind
  27005. * - BABYLON.VertexBuffer.UV2Kind
  27006. * - BABYLON.VertexBuffer.UV3Kind
  27007. * - BABYLON.VertexBuffer.UV4Kind
  27008. * - BABYLON.VertexBuffer.UV5Kind
  27009. * - BABYLON.VertexBuffer.UV6Kind
  27010. * - BABYLON.VertexBuffer.ColorKind
  27011. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27012. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27013. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27014. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27015. */
  27016. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27017. if (!this._geometry) {
  27018. if (this._delayInfo) {
  27019. return this._delayInfo.indexOf(kind) !== -1;
  27020. }
  27021. return false;
  27022. }
  27023. return this._geometry.isVerticesDataPresent(kind);
  27024. };
  27025. /**
  27026. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27027. * Possible `kind` values :
  27028. * - BABYLON.VertexBuffer.PositionKind
  27029. * - BABYLON.VertexBuffer.UVKind
  27030. * - BABYLON.VertexBuffer.UV2Kind
  27031. * - BABYLON.VertexBuffer.UV3Kind
  27032. * - BABYLON.VertexBuffer.UV4Kind
  27033. * - BABYLON.VertexBuffer.UV5Kind
  27034. * - BABYLON.VertexBuffer.UV6Kind
  27035. * - BABYLON.VertexBuffer.ColorKind
  27036. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27037. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27038. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27039. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27040. */
  27041. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27042. if (!this._geometry) {
  27043. if (this._delayInfo) {
  27044. return this._delayInfo.indexOf(kind) !== -1;
  27045. }
  27046. return false;
  27047. }
  27048. return this._geometry.isVertexBufferUpdatable(kind);
  27049. };
  27050. /**
  27051. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27052. * Possible `kind` values :
  27053. * - BABYLON.VertexBuffer.PositionKind
  27054. * - BABYLON.VertexBuffer.UVKind
  27055. * - BABYLON.VertexBuffer.UV2Kind
  27056. * - BABYLON.VertexBuffer.UV3Kind
  27057. * - BABYLON.VertexBuffer.UV4Kind
  27058. * - BABYLON.VertexBuffer.UV5Kind
  27059. * - BABYLON.VertexBuffer.UV6Kind
  27060. * - BABYLON.VertexBuffer.ColorKind
  27061. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27062. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27063. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27064. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27065. */
  27066. Mesh.prototype.getVerticesDataKinds = function () {
  27067. if (!this._geometry) {
  27068. var result = new Array();
  27069. if (this._delayInfo) {
  27070. this._delayInfo.forEach(function (kind, index, array) {
  27071. result.push(kind);
  27072. });
  27073. }
  27074. return result;
  27075. }
  27076. return this._geometry.getVerticesDataKinds();
  27077. };
  27078. /**
  27079. * Returns a positive integer : the total number of indices in this mesh geometry.
  27080. * Returns zero if the mesh has no geometry.
  27081. */
  27082. Mesh.prototype.getTotalIndices = function () {
  27083. if (!this._geometry) {
  27084. return 0;
  27085. }
  27086. return this._geometry.getTotalIndices();
  27087. };
  27088. /**
  27089. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27090. * 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.
  27091. * Returns an empty array if the mesh has no geometry.
  27092. */
  27093. Mesh.prototype.getIndices = function (copyWhenShared) {
  27094. if (!this._geometry) {
  27095. return [];
  27096. }
  27097. return this._geometry.getIndices(copyWhenShared);
  27098. };
  27099. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27100. get: function () {
  27101. return this._masterMesh !== null && this._masterMesh !== undefined;
  27102. },
  27103. enumerable: true,
  27104. configurable: true
  27105. });
  27106. /**
  27107. * Determine if the current mesh is ready to be rendered
  27108. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27109. * @returns true if all associated assets are ready (material, textures, shaders)
  27110. */
  27111. Mesh.prototype.isReady = function (forceInstanceSupport) {
  27112. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27113. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27114. return false;
  27115. }
  27116. if (!_super.prototype.isReady.call(this)) {
  27117. return false;
  27118. }
  27119. if (!this.subMeshes || this.subMeshes.length === 0) {
  27120. return true;
  27121. }
  27122. var engine = this.getEngine();
  27123. var scene = this.getScene();
  27124. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27125. this.computeWorldMatrix();
  27126. var mat = this.material || scene.defaultMaterial;
  27127. if (mat) {
  27128. if (mat.storeEffectOnSubMeshes) {
  27129. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27130. var subMesh = _a[_i];
  27131. var effectiveMaterial = subMesh.getMaterial();
  27132. if (effectiveMaterial) {
  27133. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27134. return false;
  27135. }
  27136. }
  27137. }
  27138. }
  27139. else {
  27140. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27141. return false;
  27142. }
  27143. }
  27144. }
  27145. // Shadows
  27146. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27147. var light = _c[_b];
  27148. var generator = light.getShadowGenerator();
  27149. if (generator) {
  27150. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27151. var subMesh = _e[_d];
  27152. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27153. return false;
  27154. }
  27155. }
  27156. }
  27157. }
  27158. // LOD
  27159. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27160. var lod = _g[_f];
  27161. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27162. return false;
  27163. }
  27164. }
  27165. return true;
  27166. };
  27167. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27168. /**
  27169. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27170. * This property is pertinent only for updatable parametric shapes.
  27171. */
  27172. get: function () {
  27173. return this._areNormalsFrozen;
  27174. },
  27175. enumerable: true,
  27176. configurable: true
  27177. });
  27178. /**
  27179. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27180. * It has no effect at all on other shapes.
  27181. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27182. * Returns the Mesh.
  27183. */
  27184. Mesh.prototype.freezeNormals = function () {
  27185. this._areNormalsFrozen = true;
  27186. return this;
  27187. };
  27188. /**
  27189. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27190. * It has no effect at all on other shapes.
  27191. * It reactivates the mesh normals computation if it was previously frozen.
  27192. * Returns the Mesh.
  27193. */
  27194. Mesh.prototype.unfreezeNormals = function () {
  27195. this._areNormalsFrozen = false;
  27196. return this;
  27197. };
  27198. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27199. /**
  27200. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27201. */
  27202. set: function (count) {
  27203. this._overridenInstanceCount = count;
  27204. },
  27205. enumerable: true,
  27206. configurable: true
  27207. });
  27208. // Methods
  27209. Mesh.prototype._preActivate = function () {
  27210. var sceneRenderId = this.getScene().getRenderId();
  27211. if (this._preActivateId === sceneRenderId) {
  27212. return this;
  27213. }
  27214. this._preActivateId = sceneRenderId;
  27215. this._visibleInstances = null;
  27216. return this;
  27217. };
  27218. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27219. if (this._visibleInstances) {
  27220. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27221. }
  27222. return this;
  27223. };
  27224. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27225. if (!this._visibleInstances) {
  27226. this._visibleInstances = {};
  27227. this._visibleInstances.defaultRenderId = renderId;
  27228. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27229. }
  27230. if (!this._visibleInstances[renderId]) {
  27231. this._visibleInstances[renderId] = new Array();
  27232. }
  27233. this._visibleInstances[renderId].push(instance);
  27234. return this;
  27235. };
  27236. /**
  27237. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27238. * This means the mesh underlying bounding box and sphere are recomputed.
  27239. * Returns the Mesh.
  27240. */
  27241. Mesh.prototype.refreshBoundingInfo = function () {
  27242. return this._refreshBoundingInfo(false);
  27243. };
  27244. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27245. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27246. return this;
  27247. }
  27248. var data = this._getPositionData(applySkeleton);
  27249. if (data) {
  27250. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27251. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27252. }
  27253. if (this.subMeshes) {
  27254. for (var index = 0; index < this.subMeshes.length; index++) {
  27255. this.subMeshes[index].refreshBoundingInfo();
  27256. }
  27257. }
  27258. this._updateBoundingInfo();
  27259. return this;
  27260. };
  27261. Mesh.prototype._getPositionData = function (applySkeleton) {
  27262. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27263. if (data && applySkeleton && this.skeleton) {
  27264. data = BABYLON.Tools.Slice(data);
  27265. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27266. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27267. if (matricesWeightsData && matricesIndicesData) {
  27268. var needExtras = this.numBoneInfluencers > 4;
  27269. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27270. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27271. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27272. var tempVector = BABYLON.Tmp.Vector3[0];
  27273. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27274. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27275. var matWeightIdx = 0;
  27276. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27277. finalMatrix.reset();
  27278. var inf;
  27279. var weight;
  27280. for (inf = 0; inf < 4; inf++) {
  27281. weight = matricesWeightsData[matWeightIdx + inf];
  27282. if (weight <= 0)
  27283. break;
  27284. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27285. finalMatrix.addToSelf(tempMatrix);
  27286. }
  27287. if (needExtras) {
  27288. for (inf = 0; inf < 4; inf++) {
  27289. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27290. if (weight <= 0)
  27291. break;
  27292. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27293. finalMatrix.addToSelf(tempMatrix);
  27294. }
  27295. }
  27296. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27297. tempVector.toArray(data, index);
  27298. }
  27299. }
  27300. }
  27301. return data;
  27302. };
  27303. Mesh.prototype._createGlobalSubMesh = function (force) {
  27304. var totalVertices = this.getTotalVertices();
  27305. if (!totalVertices || !this.getIndices()) {
  27306. return null;
  27307. }
  27308. // Check if we need to recreate the submeshes
  27309. if (this.subMeshes && this.subMeshes.length > 0) {
  27310. var ib = this.getIndices();
  27311. if (!ib) {
  27312. return null;
  27313. }
  27314. var totalIndices = ib.length;
  27315. var needToRecreate = false;
  27316. if (force) {
  27317. needToRecreate = true;
  27318. }
  27319. else {
  27320. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27321. var submesh = _a[_i];
  27322. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27323. needToRecreate = true;
  27324. break;
  27325. }
  27326. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27327. needToRecreate = true;
  27328. break;
  27329. }
  27330. }
  27331. }
  27332. if (!needToRecreate) {
  27333. return this.subMeshes[0];
  27334. }
  27335. }
  27336. this.releaseSubMeshes();
  27337. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27338. };
  27339. Mesh.prototype.subdivide = function (count) {
  27340. if (count < 1) {
  27341. return;
  27342. }
  27343. var totalIndices = this.getTotalIndices();
  27344. var subdivisionSize = (totalIndices / count) | 0;
  27345. var offset = 0;
  27346. // Ensure that subdivisionSize is a multiple of 3
  27347. while (subdivisionSize % 3 !== 0) {
  27348. subdivisionSize++;
  27349. }
  27350. this.releaseSubMeshes();
  27351. for (var index = 0; index < count; index++) {
  27352. if (offset >= totalIndices) {
  27353. break;
  27354. }
  27355. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27356. offset += subdivisionSize;
  27357. }
  27358. this.synchronizeInstances();
  27359. };
  27360. /**
  27361. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27362. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27363. * The `data` are either a numeric array either a Float32Array.
  27364. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27365. * 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).
  27366. * Note that a new underlying VertexBuffer object is created each call.
  27367. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27368. *
  27369. * Possible `kind` values :
  27370. * - BABYLON.VertexBuffer.PositionKind
  27371. * - BABYLON.VertexBuffer.UVKind
  27372. * - BABYLON.VertexBuffer.UV2Kind
  27373. * - BABYLON.VertexBuffer.UV3Kind
  27374. * - BABYLON.VertexBuffer.UV4Kind
  27375. * - BABYLON.VertexBuffer.UV5Kind
  27376. * - BABYLON.VertexBuffer.UV6Kind
  27377. * - BABYLON.VertexBuffer.ColorKind
  27378. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27379. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27380. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27381. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27382. *
  27383. * Returns the Mesh.
  27384. */
  27385. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27386. if (updatable === void 0) { updatable = false; }
  27387. if (!this._geometry) {
  27388. var vertexData = new BABYLON.VertexData();
  27389. vertexData.set(data, kind);
  27390. var scene = this.getScene();
  27391. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27392. }
  27393. else {
  27394. this._geometry.setVerticesData(kind, data, updatable, stride);
  27395. }
  27396. return this;
  27397. };
  27398. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27399. if (updatable === void 0) { updatable = true; }
  27400. var vb = this.getVertexBuffer(kind);
  27401. if (!vb || vb.isUpdatable() === updatable) {
  27402. return;
  27403. }
  27404. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27405. };
  27406. /**
  27407. * Sets the mesh VertexBuffer.
  27408. * Returns the Mesh.
  27409. */
  27410. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27411. if (!this._geometry) {
  27412. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27413. }
  27414. this._geometry.setVerticesBuffer(buffer);
  27415. return this;
  27416. };
  27417. /**
  27418. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27419. * If the mesh has no geometry, it is simply returned as it is.
  27420. * The `data` are either a numeric array either a Float32Array.
  27421. * No new underlying VertexBuffer object is created.
  27422. * 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.
  27423. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27424. *
  27425. * Possible `kind` values :
  27426. * - BABYLON.VertexBuffer.PositionKind
  27427. * - BABYLON.VertexBuffer.UVKind
  27428. * - BABYLON.VertexBuffer.UV2Kind
  27429. * - BABYLON.VertexBuffer.UV3Kind
  27430. * - BABYLON.VertexBuffer.UV4Kind
  27431. * - BABYLON.VertexBuffer.UV5Kind
  27432. * - BABYLON.VertexBuffer.UV6Kind
  27433. * - BABYLON.VertexBuffer.ColorKind
  27434. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27435. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27436. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27437. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27438. *
  27439. * Returns the Mesh.
  27440. */
  27441. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27442. if (!this._geometry) {
  27443. return this;
  27444. }
  27445. if (!makeItUnique) {
  27446. this._geometry.updateVerticesData(kind, data, updateExtends);
  27447. }
  27448. else {
  27449. this.makeGeometryUnique();
  27450. this.updateVerticesData(kind, data, updateExtends, false);
  27451. }
  27452. return this;
  27453. };
  27454. /**
  27455. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27456. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27457. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27458. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27459. * Returns the Mesh.
  27460. */
  27461. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27462. if (computeNormals === void 0) { computeNormals = true; }
  27463. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27464. if (!positions) {
  27465. return this;
  27466. }
  27467. positionFunction(positions);
  27468. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27469. if (computeNormals) {
  27470. var indices = this.getIndices();
  27471. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27472. if (!normals) {
  27473. return this;
  27474. }
  27475. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27476. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27477. }
  27478. return this;
  27479. };
  27480. /**
  27481. * Creates a un-shared specific occurence of the geometry for the mesh.
  27482. * Returns the Mesh.
  27483. */
  27484. Mesh.prototype.makeGeometryUnique = function () {
  27485. if (!this._geometry) {
  27486. return this;
  27487. }
  27488. var oldGeometry = this._geometry;
  27489. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27490. oldGeometry.releaseForMesh(this, true);
  27491. geometry.applyToMesh(this);
  27492. return this;
  27493. };
  27494. /**
  27495. * Sets the mesh indices.
  27496. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27497. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27498. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27499. * This method creates a new index buffer each call.
  27500. * Returns the Mesh.
  27501. */
  27502. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27503. if (totalVertices === void 0) { totalVertices = null; }
  27504. if (updatable === void 0) { updatable = false; }
  27505. if (!this._geometry) {
  27506. var vertexData = new BABYLON.VertexData();
  27507. vertexData.indices = indices;
  27508. var scene = this.getScene();
  27509. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27510. }
  27511. else {
  27512. this._geometry.setIndices(indices, totalVertices, updatable);
  27513. }
  27514. return this;
  27515. };
  27516. /**
  27517. * Update the current index buffer
  27518. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27519. * Returns the Mesh.
  27520. */
  27521. Mesh.prototype.updateIndices = function (indices, offset) {
  27522. if (!this._geometry) {
  27523. return this;
  27524. }
  27525. this._geometry.updateIndices(indices, offset);
  27526. return this;
  27527. };
  27528. /**
  27529. * Invert the geometry to move from a right handed system to a left handed one.
  27530. * Returns the Mesh.
  27531. */
  27532. Mesh.prototype.toLeftHanded = function () {
  27533. if (!this._geometry) {
  27534. return this;
  27535. }
  27536. this._geometry.toLeftHanded();
  27537. return this;
  27538. };
  27539. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27540. if (!this._geometry) {
  27541. return this;
  27542. }
  27543. var engine = this.getScene().getEngine();
  27544. // Wireframe
  27545. var indexToBind;
  27546. if (this._unIndexed) {
  27547. indexToBind = null;
  27548. }
  27549. else {
  27550. switch (fillMode) {
  27551. case BABYLON.Material.PointFillMode:
  27552. indexToBind = null;
  27553. break;
  27554. case BABYLON.Material.WireFrameFillMode:
  27555. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27556. break;
  27557. default:
  27558. case BABYLON.Material.TriangleFillMode:
  27559. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27560. break;
  27561. }
  27562. }
  27563. // VBOs
  27564. this._geometry._bind(effect, indexToBind);
  27565. return this;
  27566. };
  27567. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27568. if (alternate === void 0) { alternate = false; }
  27569. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27570. return this;
  27571. }
  27572. this.onBeforeDrawObservable.notifyObservers(this);
  27573. var scene = this.getScene();
  27574. var engine = scene.getEngine();
  27575. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27576. // or triangles as points
  27577. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27578. }
  27579. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27580. // Triangles as wireframe
  27581. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27582. }
  27583. else {
  27584. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27585. }
  27586. if (scene._isAlternateRenderingEnabled && !alternate) {
  27587. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27588. if (!effect || !scene.activeCamera) {
  27589. return this;
  27590. }
  27591. scene._switchToAlternateCameraConfiguration(true);
  27592. this._effectiveMaterial.bindView(effect);
  27593. this._effectiveMaterial.bindViewProjection(effect);
  27594. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27595. this._draw(subMesh, fillMode, instancesCount, true);
  27596. engine.setViewport(scene.activeCamera.viewport);
  27597. scene._switchToAlternateCameraConfiguration(false);
  27598. this._effectiveMaterial.bindView(effect);
  27599. this._effectiveMaterial.bindViewProjection(effect);
  27600. }
  27601. return this;
  27602. };
  27603. /**
  27604. * Registers for this mesh a javascript function called just before the rendering process.
  27605. * This function is passed the current mesh.
  27606. * Return the Mesh.
  27607. */
  27608. Mesh.prototype.registerBeforeRender = function (func) {
  27609. this.onBeforeRenderObservable.add(func);
  27610. return this;
  27611. };
  27612. /**
  27613. * Disposes a previously registered javascript function called before the rendering.
  27614. * This function is passed the current mesh.
  27615. * Returns the Mesh.
  27616. */
  27617. Mesh.prototype.unregisterBeforeRender = function (func) {
  27618. this.onBeforeRenderObservable.removeCallback(func);
  27619. return this;
  27620. };
  27621. /**
  27622. * Registers for this mesh a javascript function called just after the rendering is complete.
  27623. * This function is passed the current mesh.
  27624. * Returns the Mesh.
  27625. */
  27626. Mesh.prototype.registerAfterRender = function (func) {
  27627. this.onAfterRenderObservable.add(func);
  27628. return this;
  27629. };
  27630. /**
  27631. * Disposes a previously registered javascript function called after the rendering.
  27632. * This function is passed the current mesh.
  27633. * Return the Mesh.
  27634. */
  27635. Mesh.prototype.unregisterAfterRender = function (func) {
  27636. this.onAfterRenderObservable.removeCallback(func);
  27637. return this;
  27638. };
  27639. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27640. var scene = this.getScene();
  27641. this._batchCache.mustReturn = false;
  27642. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27643. this._batchCache.visibleInstances[subMeshId] = null;
  27644. if (this._visibleInstances) {
  27645. var currentRenderId = scene.getRenderId();
  27646. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  27647. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  27648. var selfRenderId = this._renderId;
  27649. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  27650. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  27651. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  27652. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  27653. }
  27654. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  27655. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  27656. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  27657. this._batchCache.mustReturn = true;
  27658. return this._batchCache;
  27659. }
  27660. if (currentRenderId !== selfRenderId) {
  27661. this._batchCache.renderSelf[subMeshId] = false;
  27662. }
  27663. }
  27664. this._renderIdForInstances[subMeshId] = currentRenderId;
  27665. }
  27666. return this._batchCache;
  27667. };
  27668. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  27669. var visibleInstances = batch.visibleInstances[subMesh._id];
  27670. if (!visibleInstances) {
  27671. return this;
  27672. }
  27673. var matricesCount = visibleInstances.length + 1;
  27674. var bufferSize = matricesCount * 16 * 4;
  27675. var currentInstancesBufferSize = this._instancesBufferSize;
  27676. var instancesBuffer = this._instancesBuffer;
  27677. while (this._instancesBufferSize < bufferSize) {
  27678. this._instancesBufferSize *= 2;
  27679. }
  27680. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  27681. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  27682. }
  27683. var offset = 0;
  27684. var instancesCount = 0;
  27685. var world = this.getWorldMatrix();
  27686. if (batch.renderSelf[subMesh._id]) {
  27687. world.copyToArray(this._instancesData, offset);
  27688. offset += 16;
  27689. instancesCount++;
  27690. }
  27691. if (visibleInstances) {
  27692. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  27693. var instance = visibleInstances[instanceIndex];
  27694. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  27695. offset += 16;
  27696. instancesCount++;
  27697. }
  27698. }
  27699. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  27700. if (instancesBuffer) {
  27701. instancesBuffer.dispose();
  27702. }
  27703. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27704. this._instancesBuffer = instancesBuffer;
  27705. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27706. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27707. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27708. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27709. }
  27710. else {
  27711. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  27712. }
  27713. this._bind(subMesh, effect, fillMode);
  27714. this._draw(subMesh, fillMode, instancesCount);
  27715. engine.unbindInstanceAttributes();
  27716. return this;
  27717. };
  27718. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27719. var scene = this.getScene();
  27720. var engine = scene.getEngine();
  27721. if (hardwareInstancedRendering) {
  27722. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27723. }
  27724. else {
  27725. if (batch.renderSelf[subMesh._id]) {
  27726. // Draw
  27727. if (onBeforeDraw) {
  27728. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  27729. }
  27730. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  27731. }
  27732. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  27733. if (visibleInstancesForSubMesh) {
  27734. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  27735. var instance = visibleInstancesForSubMesh[instanceIndex];
  27736. // World
  27737. var world = instance.getWorldMatrix();
  27738. if (onBeforeDraw) {
  27739. onBeforeDraw(true, world, effectiveMaterial);
  27740. }
  27741. // Draw
  27742. this._draw(subMesh, fillMode);
  27743. }
  27744. }
  27745. }
  27746. return this;
  27747. };
  27748. /**
  27749. * Triggers the draw call for the mesh.
  27750. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  27751. * Returns the Mesh.
  27752. */
  27753. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  27754. this.checkOcclusionQuery();
  27755. if (this._isOccluded) {
  27756. return this;
  27757. }
  27758. var scene = this.getScene();
  27759. // Managing instances
  27760. var batch = this._getInstancesRenderList(subMesh._id);
  27761. if (batch.mustReturn) {
  27762. return this;
  27763. }
  27764. // Checking geometry state
  27765. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27766. return this;
  27767. }
  27768. this.onBeforeRenderObservable.notifyObservers(this);
  27769. var engine = scene.getEngine();
  27770. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27771. // Material
  27772. var material = subMesh.getMaterial();
  27773. if (!material) {
  27774. return this;
  27775. }
  27776. this._effectiveMaterial = material;
  27777. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27778. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27779. return this;
  27780. }
  27781. }
  27782. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  27783. return this;
  27784. }
  27785. // Alpha mode
  27786. if (enableAlphaMode) {
  27787. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  27788. }
  27789. // Outline - step 1
  27790. var savedDepthWrite = engine.getDepthWrite();
  27791. if (this.renderOutline) {
  27792. engine.setDepthWrite(false);
  27793. scene.getOutlineRenderer().render(subMesh, batch);
  27794. engine.setDepthWrite(savedDepthWrite);
  27795. }
  27796. var effect;
  27797. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27798. effect = subMesh.effect;
  27799. }
  27800. else {
  27801. effect = this._effectiveMaterial.getEffect();
  27802. }
  27803. if (!effect) {
  27804. return this;
  27805. }
  27806. var sideOrientation = this.overrideMaterialSideOrientation;
  27807. if (sideOrientation == null) {
  27808. sideOrientation = this._effectiveMaterial.sideOrientation;
  27809. if (this._getWorldMatrixDeterminant() < 0) {
  27810. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  27811. }
  27812. }
  27813. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  27814. if (this._effectiveMaterial.forceDepthWrite) {
  27815. engine.setDepthWrite(true);
  27816. }
  27817. // Bind
  27818. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  27819. if (!hardwareInstancedRendering) {
  27820. this._bind(subMesh, effect, fillMode);
  27821. }
  27822. var world = this.getWorldMatrix();
  27823. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27824. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  27825. }
  27826. else {
  27827. this._effectiveMaterial.bind(world, this);
  27828. }
  27829. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  27830. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  27831. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27832. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  27833. }
  27834. // Draw
  27835. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27836. // Unbind
  27837. this._effectiveMaterial.unbind();
  27838. // Outline - step 2
  27839. if (this.renderOutline && savedDepthWrite) {
  27840. engine.setDepthWrite(true);
  27841. engine.setColorWrite(false);
  27842. scene.getOutlineRenderer().render(subMesh, batch);
  27843. engine.setColorWrite(true);
  27844. }
  27845. // Overlay
  27846. if (this.renderOverlay) {
  27847. var currentMode = engine.getAlphaMode();
  27848. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27849. scene.getOutlineRenderer().render(subMesh, batch, true);
  27850. engine.setAlphaMode(currentMode);
  27851. }
  27852. this.onAfterRenderObservable.notifyObservers(this);
  27853. return this;
  27854. };
  27855. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27856. if (isInstance && effectiveMaterial) {
  27857. effectiveMaterial.bindOnlyWorldMatrix(world);
  27858. }
  27859. };
  27860. /**
  27861. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27862. */
  27863. Mesh.prototype.getEmittedParticleSystems = function () {
  27864. var results = new Array();
  27865. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27866. var particleSystem = this.getScene().particleSystems[index];
  27867. if (particleSystem.emitter === this) {
  27868. results.push(particleSystem);
  27869. }
  27870. }
  27871. return results;
  27872. };
  27873. /**
  27874. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27875. */
  27876. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27877. var results = new Array();
  27878. var descendants = this.getDescendants();
  27879. descendants.push(this);
  27880. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27881. var particleSystem = this.getScene().particleSystems[index];
  27882. var emitter = particleSystem.emitter;
  27883. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27884. results.push(particleSystem);
  27885. }
  27886. }
  27887. return results;
  27888. };
  27889. Mesh.prototype._checkDelayState = function () {
  27890. var scene = this.getScene();
  27891. if (this._geometry) {
  27892. this._geometry.load(scene);
  27893. }
  27894. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27895. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27896. this._queueLoad(scene);
  27897. }
  27898. return this;
  27899. };
  27900. Mesh.prototype._queueLoad = function (scene) {
  27901. var _this = this;
  27902. scene._addPendingData(this);
  27903. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  27904. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27905. if (data instanceof ArrayBuffer) {
  27906. _this._delayLoadingFunction(data, _this);
  27907. }
  27908. else {
  27909. _this._delayLoadingFunction(JSON.parse(data), _this);
  27910. }
  27911. _this.instances.forEach(function (instance) {
  27912. instance._syncSubMeshes();
  27913. });
  27914. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27915. scene._removePendingData(_this);
  27916. }, function () { }, scene.database, getBinaryData);
  27917. return this;
  27918. };
  27919. /**
  27920. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  27921. */
  27922. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  27923. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27924. return false;
  27925. }
  27926. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  27927. return false;
  27928. }
  27929. this._checkDelayState();
  27930. return true;
  27931. };
  27932. /**
  27933. * Sets the mesh material by the material or multiMaterial `id` property.
  27934. * The material `id` is a string identifying the material or the multiMaterial.
  27935. * This method returns the Mesh.
  27936. */
  27937. Mesh.prototype.setMaterialByID = function (id) {
  27938. var materials = this.getScene().materials;
  27939. var index;
  27940. for (index = materials.length - 1; index > -1; index--) {
  27941. if (materials[index].id === id) {
  27942. this.material = materials[index];
  27943. return this;
  27944. }
  27945. }
  27946. // Multi
  27947. var multiMaterials = this.getScene().multiMaterials;
  27948. for (index = multiMaterials.length - 1; index > -1; index--) {
  27949. if (multiMaterials[index].id === id) {
  27950. this.material = multiMaterials[index];
  27951. return this;
  27952. }
  27953. }
  27954. return this;
  27955. };
  27956. /**
  27957. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  27958. */
  27959. Mesh.prototype.getAnimatables = function () {
  27960. var results = new Array();
  27961. if (this.material) {
  27962. results.push(this.material);
  27963. }
  27964. if (this.skeleton) {
  27965. results.push(this.skeleton);
  27966. }
  27967. return results;
  27968. };
  27969. /**
  27970. * Modifies the mesh geometry according to the passed transformation matrix.
  27971. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  27972. * The mesh normals are modified accordingly the same transformation.
  27973. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  27974. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27975. * Returns the Mesh.
  27976. */
  27977. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  27978. // Position
  27979. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27980. return this;
  27981. }
  27982. var submeshes = this.subMeshes.splice(0);
  27983. this._resetPointsArrayCache();
  27984. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27985. var temp = new Array();
  27986. var index;
  27987. for (index = 0; index < data.length; index += 3) {
  27988. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  27989. }
  27990. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  27991. // Normals
  27992. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27993. return this;
  27994. }
  27995. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27996. temp = [];
  27997. for (index = 0; index < data.length; index += 3) {
  27998. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  27999. }
  28000. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28001. // flip faces?
  28002. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28003. this.flipFaces();
  28004. }
  28005. // Restore submeshes
  28006. this.releaseSubMeshes();
  28007. this.subMeshes = submeshes;
  28008. return this;
  28009. };
  28010. /**
  28011. * Modifies the mesh geometry according to its own current World Matrix.
  28012. * The mesh World Matrix is then reset.
  28013. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28014. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28015. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28016. * Returns the Mesh.
  28017. */
  28018. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28019. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28020. this.scaling.copyFromFloats(1, 1, 1);
  28021. this.position.copyFromFloats(0, 0, 0);
  28022. this.rotation.copyFromFloats(0, 0, 0);
  28023. //only if quaternion is already set
  28024. if (this.rotationQuaternion) {
  28025. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28026. }
  28027. this._worldMatrix = BABYLON.Matrix.Identity();
  28028. return this;
  28029. };
  28030. Object.defineProperty(Mesh.prototype, "_positions", {
  28031. // Cache
  28032. get: function () {
  28033. if (this._geometry) {
  28034. return this._geometry._positions;
  28035. }
  28036. return null;
  28037. },
  28038. enumerable: true,
  28039. configurable: true
  28040. });
  28041. Mesh.prototype._resetPointsArrayCache = function () {
  28042. if (this._geometry) {
  28043. this._geometry._resetPointsArrayCache();
  28044. }
  28045. return this;
  28046. };
  28047. Mesh.prototype._generatePointsArray = function () {
  28048. if (this._geometry) {
  28049. return this._geometry._generatePointsArray();
  28050. }
  28051. return false;
  28052. };
  28053. /**
  28054. * Returns a new Mesh object generated from the current mesh properties.
  28055. * This method must not get confused with createInstance().
  28056. * The parameter `name` is a string, the name given to the new mesh.
  28057. * The optional parameter `newParent` can be any Node object (default `null`).
  28058. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28059. * 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.
  28060. */
  28061. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28062. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28063. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28064. };
  28065. /**
  28066. * Disposes the Mesh.
  28067. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28068. * Returns nothing.
  28069. */
  28070. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28071. var _this = this;
  28072. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28073. this.morphTargetManager = null;
  28074. if (this._geometry) {
  28075. this._geometry.releaseForMesh(this, true);
  28076. }
  28077. // Sources
  28078. var meshes = this.getScene().meshes;
  28079. meshes.forEach(function (abstractMesh) {
  28080. var mesh = abstractMesh;
  28081. if (mesh._source && mesh._source === _this) {
  28082. mesh._source = null;
  28083. }
  28084. });
  28085. this._source = null;
  28086. // Instances
  28087. if (this._instancesBuffer) {
  28088. this._instancesBuffer.dispose();
  28089. this._instancesBuffer = null;
  28090. }
  28091. while (this.instances.length) {
  28092. this.instances[0].dispose();
  28093. }
  28094. // Effect layers.
  28095. var effectLayers = this.getScene().effectLayers;
  28096. for (var i = 0; i < effectLayers.length; i++) {
  28097. var effectLayer = effectLayers[i];
  28098. if (effectLayer) {
  28099. effectLayer._disposeMesh(this);
  28100. }
  28101. }
  28102. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28103. };
  28104. /**
  28105. * Modifies the mesh geometry according to a displacement map.
  28106. * 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.
  28107. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28108. * This method returns nothing.
  28109. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28110. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28111. * 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.
  28112. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28113. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28114. *
  28115. * Returns the Mesh.
  28116. */
  28117. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28118. var _this = this;
  28119. var scene = this.getScene();
  28120. var onload = function (img) {
  28121. // Getting height map data
  28122. var canvas = document.createElement("canvas");
  28123. var context = canvas.getContext("2d");
  28124. var heightMapWidth = img.width;
  28125. var heightMapHeight = img.height;
  28126. canvas.width = heightMapWidth;
  28127. canvas.height = heightMapHeight;
  28128. context.drawImage(img, 0, 0);
  28129. // Create VertexData from map data
  28130. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28131. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28132. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28133. //execute success callback, if set
  28134. if (onSuccess) {
  28135. onSuccess(_this);
  28136. }
  28137. };
  28138. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28139. return this;
  28140. };
  28141. /**
  28142. * Modifies the mesh geometry according to a displacementMap buffer.
  28143. * 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.
  28144. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28145. * This method returns nothing.
  28146. * 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.
  28147. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28148. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28149. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28150. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28151. *
  28152. * Returns the Mesh.
  28153. */
  28154. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28155. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28156. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28157. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28158. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28159. return this;
  28160. }
  28161. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28162. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28163. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28164. var position = BABYLON.Vector3.Zero();
  28165. var normal = BABYLON.Vector3.Zero();
  28166. var uv = BABYLON.Vector2.Zero();
  28167. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28168. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28169. for (var index = 0; index < positions.length; index += 3) {
  28170. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28171. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28172. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28173. // Compute height
  28174. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28175. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28176. var pos = (u + v * heightMapWidth) * 4;
  28177. var r = buffer[pos] / 255.0;
  28178. var g = buffer[pos + 1] / 255.0;
  28179. var b = buffer[pos + 2] / 255.0;
  28180. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28181. normal.normalize();
  28182. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28183. position = position.add(normal);
  28184. position.toArray(positions, index);
  28185. }
  28186. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28187. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28188. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28189. return this;
  28190. };
  28191. /**
  28192. * Modify the mesh to get a flat shading rendering.
  28193. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28194. * This method returns the Mesh.
  28195. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28196. */
  28197. Mesh.prototype.convertToFlatShadedMesh = function () {
  28198. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28199. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28200. var kinds = this.getVerticesDataKinds();
  28201. var vbs = {};
  28202. var data = {};
  28203. var newdata = {};
  28204. var updatableNormals = false;
  28205. var kindIndex;
  28206. var kind;
  28207. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28208. kind = kinds[kindIndex];
  28209. var vertexBuffer = this.getVertexBuffer(kind);
  28210. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28211. updatableNormals = vertexBuffer.isUpdatable();
  28212. kinds.splice(kindIndex, 1);
  28213. kindIndex--;
  28214. continue;
  28215. }
  28216. vbs[kind] = vertexBuffer;
  28217. data[kind] = vbs[kind].getData();
  28218. newdata[kind] = [];
  28219. }
  28220. // Save previous submeshes
  28221. var previousSubmeshes = this.subMeshes.slice(0);
  28222. var indices = this.getIndices();
  28223. var totalIndices = this.getTotalIndices();
  28224. // Generating unique vertices per face
  28225. var index;
  28226. for (index = 0; index < totalIndices; index++) {
  28227. var vertexIndex = indices[index];
  28228. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28229. kind = kinds[kindIndex];
  28230. var stride = vbs[kind].getStrideSize();
  28231. for (var offset = 0; offset < stride; offset++) {
  28232. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28233. }
  28234. }
  28235. }
  28236. // Updating faces & normal
  28237. var normals = [];
  28238. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28239. for (index = 0; index < totalIndices; index += 3) {
  28240. indices[index] = index;
  28241. indices[index + 1] = index + 1;
  28242. indices[index + 2] = index + 2;
  28243. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28244. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28245. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28246. var p1p2 = p1.subtract(p2);
  28247. var p3p2 = p3.subtract(p2);
  28248. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28249. // Store same normals for every vertex
  28250. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28251. normals.push(normal.x);
  28252. normals.push(normal.y);
  28253. normals.push(normal.z);
  28254. }
  28255. }
  28256. this.setIndices(indices);
  28257. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28258. // Updating vertex buffers
  28259. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28260. kind = kinds[kindIndex];
  28261. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28262. }
  28263. // Updating submeshes
  28264. this.releaseSubMeshes();
  28265. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28266. var previousOne = previousSubmeshes[submeshIndex];
  28267. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28268. }
  28269. this.synchronizeInstances();
  28270. return this;
  28271. };
  28272. /**
  28273. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28274. * In other words, more vertices, no more indices and a single bigger VBO.
  28275. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28276. * Returns the Mesh.
  28277. */
  28278. Mesh.prototype.convertToUnIndexedMesh = function () {
  28279. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28280. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28281. var kinds = this.getVerticesDataKinds();
  28282. var vbs = {};
  28283. var data = {};
  28284. var newdata = {};
  28285. var kindIndex;
  28286. var kind;
  28287. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28288. kind = kinds[kindIndex];
  28289. var vertexBuffer = this.getVertexBuffer(kind);
  28290. vbs[kind] = vertexBuffer;
  28291. data[kind] = vbs[kind].getData();
  28292. newdata[kind] = [];
  28293. }
  28294. // Save previous submeshes
  28295. var previousSubmeshes = this.subMeshes.slice(0);
  28296. var indices = this.getIndices();
  28297. var totalIndices = this.getTotalIndices();
  28298. // Generating unique vertices per face
  28299. var index;
  28300. for (index = 0; index < totalIndices; index++) {
  28301. var vertexIndex = indices[index];
  28302. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28303. kind = kinds[kindIndex];
  28304. var stride = vbs[kind].getStrideSize();
  28305. for (var offset = 0; offset < stride; offset++) {
  28306. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28307. }
  28308. }
  28309. }
  28310. // Updating indices
  28311. for (index = 0; index < totalIndices; index += 3) {
  28312. indices[index] = index;
  28313. indices[index + 1] = index + 1;
  28314. indices[index + 2] = index + 2;
  28315. }
  28316. this.setIndices(indices);
  28317. // Updating vertex buffers
  28318. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28319. kind = kinds[kindIndex];
  28320. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28321. }
  28322. // Updating submeshes
  28323. this.releaseSubMeshes();
  28324. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28325. var previousOne = previousSubmeshes[submeshIndex];
  28326. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28327. }
  28328. this._unIndexed = true;
  28329. this.synchronizeInstances();
  28330. return this;
  28331. };
  28332. /**
  28333. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28334. * This method returns the Mesh.
  28335. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28336. */
  28337. Mesh.prototype.flipFaces = function (flipNormals) {
  28338. if (flipNormals === void 0) { flipNormals = false; }
  28339. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28340. var i;
  28341. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28342. for (i = 0; i < vertex_data.normals.length; i++) {
  28343. vertex_data.normals[i] *= -1;
  28344. }
  28345. }
  28346. if (vertex_data.indices) {
  28347. var temp;
  28348. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28349. // reassign indices
  28350. temp = vertex_data.indices[i + 1];
  28351. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28352. vertex_data.indices[i + 2] = temp;
  28353. }
  28354. }
  28355. vertex_data.applyToMesh(this);
  28356. return this;
  28357. };
  28358. // Instances
  28359. /**
  28360. * Creates a new InstancedMesh object from the mesh model.
  28361. * An instance shares the same properties and the same material than its model.
  28362. * Only these properties of each instance can then be set individually :
  28363. * - position
  28364. * - rotation
  28365. * - rotationQuaternion
  28366. * - setPivotMatrix
  28367. * - scaling
  28368. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28369. * Warning : this method is not supported for Line mesh and LineSystem
  28370. */
  28371. Mesh.prototype.createInstance = function (name) {
  28372. return new BABYLON.InstancedMesh(name, this);
  28373. };
  28374. /**
  28375. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28376. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28377. * This method returns the Mesh.
  28378. */
  28379. Mesh.prototype.synchronizeInstances = function () {
  28380. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28381. var instance = this.instances[instanceIndex];
  28382. instance._syncSubMeshes();
  28383. }
  28384. return this;
  28385. };
  28386. /**
  28387. * Simplify the mesh according to the given array of settings.
  28388. * Function will return immediately and will simplify async. It returns the Mesh.
  28389. * @param settings a collection of simplification settings.
  28390. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28391. * @param type the type of simplification to run.
  28392. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28393. */
  28394. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28395. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28396. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28397. this.getScene().simplificationQueue.addTask({
  28398. settings: settings,
  28399. parallelProcessing: parallelProcessing,
  28400. mesh: this,
  28401. simplificationType: simplificationType,
  28402. successCallback: successCallback
  28403. });
  28404. return this;
  28405. };
  28406. /**
  28407. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28408. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28409. * This should be used together with the simplification to avoid disappearing triangles.
  28410. * Returns the Mesh.
  28411. * @param successCallback an optional success callback to be called after the optimization finished.
  28412. */
  28413. Mesh.prototype.optimizeIndices = function (successCallback) {
  28414. var _this = this;
  28415. var indices = this.getIndices();
  28416. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28417. if (!positions || !indices) {
  28418. return this;
  28419. }
  28420. var vectorPositions = new Array();
  28421. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28422. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28423. }
  28424. var dupes = new Array();
  28425. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28426. var realPos = vectorPositions.length - 1 - iteration;
  28427. var testedPosition = vectorPositions[realPos];
  28428. for (var j = 0; j < realPos; ++j) {
  28429. var againstPosition = vectorPositions[j];
  28430. if (testedPosition.equals(againstPosition)) {
  28431. dupes[realPos] = j;
  28432. break;
  28433. }
  28434. }
  28435. }, function () {
  28436. for (var i = 0; i < indices.length; ++i) {
  28437. indices[i] = dupes[indices[i]] || indices[i];
  28438. }
  28439. //indices are now reordered
  28440. var originalSubMeshes = _this.subMeshes.slice(0);
  28441. _this.setIndices(indices);
  28442. _this.subMeshes = originalSubMeshes;
  28443. if (successCallback) {
  28444. successCallback(_this);
  28445. }
  28446. });
  28447. return this;
  28448. };
  28449. Mesh.prototype.serialize = function (serializationObject) {
  28450. serializationObject.name = this.name;
  28451. serializationObject.id = this.id;
  28452. serializationObject.type = this.getClassName();
  28453. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28454. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28455. }
  28456. serializationObject.position = this.position.asArray();
  28457. if (this.rotationQuaternion) {
  28458. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28459. }
  28460. else if (this.rotation) {
  28461. serializationObject.rotation = this.rotation.asArray();
  28462. }
  28463. serializationObject.scaling = this.scaling.asArray();
  28464. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28465. serializationObject.isEnabled = this.isEnabled(false);
  28466. serializationObject.isVisible = this.isVisible;
  28467. serializationObject.infiniteDistance = this.infiniteDistance;
  28468. serializationObject.pickable = this.isPickable;
  28469. serializationObject.receiveShadows = this.receiveShadows;
  28470. serializationObject.billboardMode = this.billboardMode;
  28471. serializationObject.visibility = this.visibility;
  28472. serializationObject.checkCollisions = this.checkCollisions;
  28473. serializationObject.isBlocker = this.isBlocker;
  28474. // Parent
  28475. if (this.parent) {
  28476. serializationObject.parentId = this.parent.id;
  28477. }
  28478. // Geometry
  28479. serializationObject.isUnIndexed = this.isUnIndexed;
  28480. var geometry = this._geometry;
  28481. if (geometry) {
  28482. var geometryId = geometry.id;
  28483. serializationObject.geometryId = geometryId;
  28484. // SubMeshes
  28485. serializationObject.subMeshes = [];
  28486. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28487. var subMesh = this.subMeshes[subIndex];
  28488. serializationObject.subMeshes.push({
  28489. materialIndex: subMesh.materialIndex,
  28490. verticesStart: subMesh.verticesStart,
  28491. verticesCount: subMesh.verticesCount,
  28492. indexStart: subMesh.indexStart,
  28493. indexCount: subMesh.indexCount
  28494. });
  28495. }
  28496. }
  28497. // Material
  28498. if (this.material) {
  28499. serializationObject.materialId = this.material.id;
  28500. }
  28501. else {
  28502. this.material = null;
  28503. }
  28504. // Morph targets
  28505. if (this.morphTargetManager) {
  28506. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28507. }
  28508. // Skeleton
  28509. if (this.skeleton) {
  28510. serializationObject.skeletonId = this.skeleton.id;
  28511. }
  28512. // Physics
  28513. //TODO implement correct serialization for physics impostors.
  28514. var impostor = this.getPhysicsImpostor();
  28515. if (impostor) {
  28516. serializationObject.physicsMass = impostor.getParam("mass");
  28517. serializationObject.physicsFriction = impostor.getParam("friction");
  28518. serializationObject.physicsRestitution = impostor.getParam("mass");
  28519. serializationObject.physicsImpostor = impostor.type;
  28520. }
  28521. // Metadata
  28522. if (this.metadata) {
  28523. serializationObject.metadata = this.metadata;
  28524. }
  28525. // Instances
  28526. serializationObject.instances = [];
  28527. for (var index = 0; index < this.instances.length; index++) {
  28528. var instance = this.instances[index];
  28529. var serializationInstance = {
  28530. name: instance.name,
  28531. id: instance.id,
  28532. position: instance.position.asArray(),
  28533. scaling: instance.scaling.asArray()
  28534. };
  28535. if (instance.rotationQuaternion) {
  28536. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28537. }
  28538. else if (instance.rotation) {
  28539. serializationInstance.rotation = instance.rotation.asArray();
  28540. }
  28541. serializationObject.instances.push(serializationInstance);
  28542. // Animations
  28543. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28544. serializationInstance.ranges = instance.serializeAnimationRanges();
  28545. }
  28546. //
  28547. // Animations
  28548. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28549. serializationObject.ranges = this.serializeAnimationRanges();
  28550. // Layer mask
  28551. serializationObject.layerMask = this.layerMask;
  28552. // Alpha
  28553. serializationObject.alphaIndex = this.alphaIndex;
  28554. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28555. // Overlay
  28556. serializationObject.overlayAlpha = this.overlayAlpha;
  28557. serializationObject.overlayColor = this.overlayColor.asArray();
  28558. serializationObject.renderOverlay = this.renderOverlay;
  28559. // Fog
  28560. serializationObject.applyFog = this.applyFog;
  28561. // Action Manager
  28562. if (this.actionManager) {
  28563. serializationObject.actions = this.actionManager.serialize(this.name);
  28564. }
  28565. };
  28566. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28567. if (!this.geometry) {
  28568. return;
  28569. }
  28570. this._markSubMeshesAsAttributesDirty();
  28571. var morphTargetManager = this._morphTargetManager;
  28572. if (morphTargetManager && morphTargetManager.vertexCount) {
  28573. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28574. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28575. this.morphTargetManager = null;
  28576. return;
  28577. }
  28578. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28579. var morphTarget = morphTargetManager.getActiveTarget(index);
  28580. var positions = morphTarget.getPositions();
  28581. if (!positions) {
  28582. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28583. return;
  28584. }
  28585. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28586. var normals = morphTarget.getNormals();
  28587. if (normals) {
  28588. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28589. }
  28590. var tangents = morphTarget.getTangents();
  28591. if (tangents) {
  28592. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28593. }
  28594. }
  28595. }
  28596. else {
  28597. var index = 0;
  28598. // Positions
  28599. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28600. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28601. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28602. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28603. }
  28604. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28605. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28606. }
  28607. index++;
  28608. }
  28609. }
  28610. };
  28611. // Statics
  28612. /**
  28613. * Returns a new Mesh object parsed from the source provided.
  28614. * The parameter `parsedMesh` is the source.
  28615. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28616. */
  28617. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28618. var mesh;
  28619. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28620. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28621. }
  28622. else {
  28623. mesh = new Mesh(parsedMesh.name, scene);
  28624. }
  28625. mesh.id = parsedMesh.id;
  28626. if (BABYLON.Tags) {
  28627. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28628. }
  28629. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28630. if (parsedMesh.metadata !== undefined) {
  28631. mesh.metadata = parsedMesh.metadata;
  28632. }
  28633. if (parsedMesh.rotationQuaternion) {
  28634. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28635. }
  28636. else if (parsedMesh.rotation) {
  28637. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28638. }
  28639. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28640. if (parsedMesh.localMatrix) {
  28641. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28642. }
  28643. else if (parsedMesh.pivotMatrix) {
  28644. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28645. }
  28646. mesh.setEnabled(parsedMesh.isEnabled);
  28647. mesh.isVisible = parsedMesh.isVisible;
  28648. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  28649. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  28650. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  28651. if (parsedMesh.applyFog !== undefined) {
  28652. mesh.applyFog = parsedMesh.applyFog;
  28653. }
  28654. if (parsedMesh.pickable !== undefined) {
  28655. mesh.isPickable = parsedMesh.pickable;
  28656. }
  28657. if (parsedMesh.alphaIndex !== undefined) {
  28658. mesh.alphaIndex = parsedMesh.alphaIndex;
  28659. }
  28660. mesh.receiveShadows = parsedMesh.receiveShadows;
  28661. mesh.billboardMode = parsedMesh.billboardMode;
  28662. if (parsedMesh.visibility !== undefined) {
  28663. mesh.visibility = parsedMesh.visibility;
  28664. }
  28665. mesh.checkCollisions = parsedMesh.checkCollisions;
  28666. if (parsedMesh.isBlocker !== undefined) {
  28667. mesh.isBlocker = parsedMesh.isBlocker;
  28668. }
  28669. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  28670. // freezeWorldMatrix
  28671. if (parsedMesh.freezeWorldMatrix) {
  28672. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  28673. }
  28674. // Parent
  28675. if (parsedMesh.parentId) {
  28676. mesh._waitingParentId = parsedMesh.parentId;
  28677. }
  28678. // Actions
  28679. if (parsedMesh.actions !== undefined) {
  28680. mesh._waitingActions = parsedMesh.actions;
  28681. }
  28682. // Overlay
  28683. if (parsedMesh.overlayAlpha !== undefined) {
  28684. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  28685. }
  28686. if (parsedMesh.overlayColor !== undefined) {
  28687. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  28688. }
  28689. if (parsedMesh.renderOverlay !== undefined) {
  28690. mesh.renderOverlay = parsedMesh.renderOverlay;
  28691. }
  28692. // Geometry
  28693. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  28694. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  28695. if (parsedMesh.delayLoadingFile) {
  28696. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28697. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  28698. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  28699. if (parsedMesh._binaryInfo) {
  28700. mesh._binaryInfo = parsedMesh._binaryInfo;
  28701. }
  28702. mesh._delayInfo = [];
  28703. if (parsedMesh.hasUVs) {
  28704. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28705. }
  28706. if (parsedMesh.hasUVs2) {
  28707. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28708. }
  28709. if (parsedMesh.hasUVs3) {
  28710. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28711. }
  28712. if (parsedMesh.hasUVs4) {
  28713. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28714. }
  28715. if (parsedMesh.hasUVs5) {
  28716. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28717. }
  28718. if (parsedMesh.hasUVs6) {
  28719. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28720. }
  28721. if (parsedMesh.hasColors) {
  28722. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28723. }
  28724. if (parsedMesh.hasMatricesIndices) {
  28725. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28726. }
  28727. if (parsedMesh.hasMatricesWeights) {
  28728. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28729. }
  28730. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  28731. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  28732. mesh._checkDelayState();
  28733. }
  28734. }
  28735. else {
  28736. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  28737. }
  28738. // Material
  28739. if (parsedMesh.materialId) {
  28740. mesh.setMaterialByID(parsedMesh.materialId);
  28741. }
  28742. else {
  28743. mesh.material = null;
  28744. }
  28745. // Morph targets
  28746. if (parsedMesh.morphTargetManagerId > -1) {
  28747. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  28748. }
  28749. // Skeleton
  28750. if (parsedMesh.skeletonId > -1) {
  28751. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  28752. if (parsedMesh.numBoneInfluencers) {
  28753. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  28754. }
  28755. }
  28756. // Animations
  28757. if (parsedMesh.animations) {
  28758. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28759. var parsedAnimation = parsedMesh.animations[animationIndex];
  28760. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28761. }
  28762. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  28763. }
  28764. if (parsedMesh.autoAnimate) {
  28765. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  28766. }
  28767. // Layer Mask
  28768. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  28769. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  28770. }
  28771. else {
  28772. mesh.layerMask = 0x0FFFFFFF;
  28773. }
  28774. // Physics
  28775. if (parsedMesh.physicsImpostor) {
  28776. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  28777. mass: parsedMesh.physicsMass,
  28778. friction: parsedMesh.physicsFriction,
  28779. restitution: parsedMesh.physicsRestitution
  28780. }, scene);
  28781. }
  28782. // Instances
  28783. if (parsedMesh.instances) {
  28784. for (var index = 0; index < parsedMesh.instances.length; index++) {
  28785. var parsedInstance = parsedMesh.instances[index];
  28786. var instance = mesh.createInstance(parsedInstance.name);
  28787. if (parsedInstance.id) {
  28788. instance.id = parsedInstance.id;
  28789. }
  28790. if (BABYLON.Tags) {
  28791. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  28792. }
  28793. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  28794. if (parsedInstance.parentId) {
  28795. instance._waitingParentId = parsedInstance.parentId;
  28796. }
  28797. if (parsedInstance.rotationQuaternion) {
  28798. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  28799. }
  28800. else if (parsedInstance.rotation) {
  28801. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  28802. }
  28803. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  28804. instance.checkCollisions = mesh.checkCollisions;
  28805. if (parsedMesh.animations) {
  28806. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28807. parsedAnimation = parsedMesh.animations[animationIndex];
  28808. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28809. }
  28810. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  28811. }
  28812. }
  28813. }
  28814. return mesh;
  28815. };
  28816. /**
  28817. * Creates a ribbon mesh.
  28818. * Please consider using the same method from the MeshBuilder class instead.
  28819. * 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.
  28820. *
  28821. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28822. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28823. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28824. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28825. * 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.
  28826. * 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.
  28827. * 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
  28828. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28829. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28830. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28831. */
  28832. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  28833. if (closeArray === void 0) { closeArray = false; }
  28834. if (updatable === void 0) { updatable = false; }
  28835. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28836. pathArray: pathArray,
  28837. closeArray: closeArray,
  28838. closePath: closePath,
  28839. offset: offset,
  28840. updatable: updatable,
  28841. sideOrientation: sideOrientation,
  28842. instance: instance
  28843. }, scene);
  28844. };
  28845. /**
  28846. * Creates a plane polygonal mesh. By default, this is a disc.
  28847. * Please consider using the same method from the MeshBuilder class instead.
  28848. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28849. * 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.
  28850. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28851. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28852. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28853. */
  28854. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28855. if (scene === void 0) { scene = null; }
  28856. var options = {
  28857. radius: radius,
  28858. tessellation: tessellation,
  28859. sideOrientation: sideOrientation,
  28860. updatable: updatable
  28861. };
  28862. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28863. };
  28864. /**
  28865. * Creates a box mesh.
  28866. * Please consider using the same method from the MeshBuilder class instead.
  28867. * The parameter `size` sets the size (float) of each box side (default 1).
  28868. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28869. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28870. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28871. */
  28872. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28873. if (scene === void 0) { scene = null; }
  28874. var options = {
  28875. size: size,
  28876. sideOrientation: sideOrientation,
  28877. updatable: updatable
  28878. };
  28879. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28880. };
  28881. /**
  28882. * Creates a sphere mesh.
  28883. * Please consider using the same method from the MeshBuilder class instead.
  28884. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28885. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28886. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28887. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28888. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28889. */
  28890. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28891. var options = {
  28892. segments: segments,
  28893. diameterX: diameter,
  28894. diameterY: diameter,
  28895. diameterZ: diameter,
  28896. sideOrientation: sideOrientation,
  28897. updatable: updatable
  28898. };
  28899. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  28900. };
  28901. /**
  28902. * Creates a cylinder or a cone mesh.
  28903. * Please consider using the same method from the MeshBuilder class instead.
  28904. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28905. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28906. * 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.
  28907. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28908. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28909. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28910. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28911. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28912. */
  28913. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  28914. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  28915. if (scene !== undefined) {
  28916. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  28917. updatable = scene;
  28918. }
  28919. scene = subdivisions;
  28920. subdivisions = 1;
  28921. }
  28922. var options = {
  28923. height: height,
  28924. diameterTop: diameterTop,
  28925. diameterBottom: diameterBottom,
  28926. tessellation: tessellation,
  28927. subdivisions: subdivisions,
  28928. sideOrientation: sideOrientation,
  28929. updatable: updatable
  28930. };
  28931. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  28932. };
  28933. // Torus (Code from SharpDX.org)
  28934. /**
  28935. * Creates a torus mesh.
  28936. * Please consider using the same method from the MeshBuilder class instead.
  28937. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28938. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28939. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28940. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28941. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28942. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28943. */
  28944. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  28945. var options = {
  28946. diameter: diameter,
  28947. thickness: thickness,
  28948. tessellation: tessellation,
  28949. sideOrientation: sideOrientation,
  28950. updatable: updatable
  28951. };
  28952. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  28953. };
  28954. /**
  28955. * Creates a torus knot mesh.
  28956. * Please consider using the same method from the MeshBuilder class instead.
  28957. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28958. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28959. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28960. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28961. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28962. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28963. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28964. */
  28965. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  28966. var options = {
  28967. radius: radius,
  28968. tube: tube,
  28969. radialSegments: radialSegments,
  28970. tubularSegments: tubularSegments,
  28971. p: p,
  28972. q: q,
  28973. sideOrientation: sideOrientation,
  28974. updatable: updatable
  28975. };
  28976. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  28977. };
  28978. /**
  28979. * Creates a line mesh.
  28980. * Please consider using the same method from the MeshBuilder class instead.
  28981. * 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.
  28982. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28983. * The parameter `points` is an array successive Vector3.
  28984. * 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
  28985. * When updating an instance, remember that only point positions can change, not the number of points.
  28986. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28987. */
  28988. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  28989. if (scene === void 0) { scene = null; }
  28990. if (updatable === void 0) { updatable = false; }
  28991. if (instance === void 0) { instance = null; }
  28992. var options = {
  28993. points: points,
  28994. updatable: updatable,
  28995. instance: instance
  28996. };
  28997. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  28998. };
  28999. /**
  29000. * Creates a dashed line mesh.
  29001. * Please consider using the same method from the MeshBuilder class instead.
  29002. * 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.
  29003. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29004. * The parameter `points` is an array successive Vector3.
  29005. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29006. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29007. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29008. * 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
  29009. * When updating an instance, remember that only point positions can change, not the number of points.
  29010. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29011. */
  29012. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29013. if (scene === void 0) { scene = null; }
  29014. var options = {
  29015. points: points,
  29016. dashSize: dashSize,
  29017. gapSize: gapSize,
  29018. dashNb: dashNb,
  29019. updatable: updatable,
  29020. instance: instance
  29021. };
  29022. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29023. };
  29024. /**
  29025. * Creates a polygon mesh.
  29026. * Please consider using the same method from the MeshBuilder class instead.
  29027. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29028. * 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.
  29029. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29030. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29031. * Remember you can only change the shape positions, not their number when updating a polygon.
  29032. */
  29033. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29034. var options = {
  29035. shape: shape,
  29036. holes: holes,
  29037. updatable: updatable,
  29038. sideOrientation: sideOrientation
  29039. };
  29040. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29041. };
  29042. /**
  29043. * Creates an extruded polygon mesh, with depth in the Y direction.
  29044. * Please consider using the same method from the MeshBuilder class instead.
  29045. */
  29046. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29047. var options = {
  29048. shape: shape,
  29049. holes: holes,
  29050. depth: depth,
  29051. updatable: updatable,
  29052. sideOrientation: sideOrientation
  29053. };
  29054. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29055. };
  29056. /**
  29057. * Creates an extruded shape mesh.
  29058. * 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.
  29059. * Please consider using the same method from the MeshBuilder class instead.
  29060. *
  29061. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29062. * 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
  29063. * extruded along the Z axis.
  29064. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29065. * 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.
  29066. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29067. * 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
  29068. * 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
  29069. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29070. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29071. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29072. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29073. */
  29074. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29075. if (scene === void 0) { scene = null; }
  29076. var options = {
  29077. shape: shape,
  29078. path: path,
  29079. scale: scale,
  29080. rotation: rotation,
  29081. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29082. sideOrientation: sideOrientation,
  29083. instance: instance,
  29084. updatable: updatable
  29085. };
  29086. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29087. };
  29088. /**
  29089. * Creates an custom extruded shape mesh.
  29090. * 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.
  29091. * Please consider using the same method from the MeshBuilder class instead.
  29092. *
  29093. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29094. * 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
  29095. * extruded along the Z axis.
  29096. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29097. * 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
  29098. * and the distance of this point from the begining of the path :
  29099. * ```javascript
  29100. * var rotationFunction = function(i, distance) {
  29101. * // do things
  29102. * return rotationValue; }
  29103. * ```
  29104. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29105. * 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
  29106. * and the distance of this point from the begining of the path :
  29107. * ```javascript
  29108. * var scaleFunction = function(i, distance) {
  29109. * // do things
  29110. * return scaleValue;}
  29111. * ```
  29112. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29113. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29114. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29115. * 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
  29116. * 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
  29117. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29118. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29119. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29120. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29121. */
  29122. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29123. var options = {
  29124. shape: shape,
  29125. path: path,
  29126. scaleFunction: scaleFunction,
  29127. rotationFunction: rotationFunction,
  29128. ribbonCloseArray: ribbonCloseArray,
  29129. ribbonClosePath: ribbonClosePath,
  29130. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29131. sideOrientation: sideOrientation,
  29132. instance: instance,
  29133. updatable: updatable
  29134. };
  29135. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29136. };
  29137. /**
  29138. * Creates lathe mesh.
  29139. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29140. * Please consider using the same method from the MeshBuilder class instead.
  29141. * 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
  29142. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29143. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29144. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29145. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29146. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29147. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29148. */
  29149. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29150. var options = {
  29151. shape: shape,
  29152. radius: radius,
  29153. tessellation: tessellation,
  29154. sideOrientation: sideOrientation,
  29155. updatable: updatable
  29156. };
  29157. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29158. };
  29159. /**
  29160. * Creates a plane mesh.
  29161. * Please consider using the same method from the MeshBuilder class instead.
  29162. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29163. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29164. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29165. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29166. */
  29167. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29168. var options = {
  29169. size: size,
  29170. width: size,
  29171. height: size,
  29172. sideOrientation: sideOrientation,
  29173. updatable: updatable
  29174. };
  29175. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29176. };
  29177. /**
  29178. * Creates a ground mesh.
  29179. * Please consider using the same method from the MeshBuilder class instead.
  29180. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29181. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29183. */
  29184. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29185. var options = {
  29186. width: width,
  29187. height: height,
  29188. subdivisions: subdivisions,
  29189. updatable: updatable
  29190. };
  29191. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29192. };
  29193. /**
  29194. * Creates a tiled ground mesh.
  29195. * Please consider using the same method from the MeshBuilder class instead.
  29196. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29197. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29198. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29199. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29200. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29201. * numbers of subdivisions on the ground width and height of each tile.
  29202. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29203. */
  29204. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29205. var options = {
  29206. xmin: xmin,
  29207. zmin: zmin,
  29208. xmax: xmax,
  29209. zmax: zmax,
  29210. subdivisions: subdivisions,
  29211. precision: precision,
  29212. updatable: updatable
  29213. };
  29214. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29215. };
  29216. /**
  29217. * Creates a ground mesh from a height map.
  29218. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29219. * Please consider using the same method from the MeshBuilder class instead.
  29220. * The parameter `url` sets the URL of the height map image resource.
  29221. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29222. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29223. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29224. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29225. * 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).
  29226. * This function is passed the newly built mesh :
  29227. * ```javascript
  29228. * function(mesh) { // do things
  29229. * return; }
  29230. * ```
  29231. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29232. */
  29233. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29234. var options = {
  29235. width: width,
  29236. height: height,
  29237. subdivisions: subdivisions,
  29238. minHeight: minHeight,
  29239. maxHeight: maxHeight,
  29240. updatable: updatable,
  29241. onReady: onReady
  29242. };
  29243. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29244. };
  29245. /**
  29246. * Creates a tube mesh.
  29247. * 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.
  29248. * Please consider using the same method from the MeshBuilder class instead.
  29249. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29250. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29251. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29252. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29253. * 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.
  29254. * It must return a radius value (positive float) :
  29255. * ```javascript
  29256. * var radiusFunction = function(i, distance) {
  29257. * // do things
  29258. * return radius; }
  29259. * ```
  29260. * 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
  29261. * 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
  29262. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29263. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29264. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29265. */
  29266. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29267. var options = {
  29268. path: path,
  29269. radius: radius,
  29270. tessellation: tessellation,
  29271. radiusFunction: radiusFunction,
  29272. arc: 1,
  29273. cap: cap,
  29274. updatable: updatable,
  29275. sideOrientation: sideOrientation,
  29276. instance: instance
  29277. };
  29278. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29279. };
  29280. /**
  29281. * Creates a polyhedron mesh.
  29282. * Please consider using the same method from the MeshBuilder class instead.
  29283. * 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
  29284. * to choose the wanted type.
  29285. * The parameter `size` (positive float, default 1) sets the polygon size.
  29286. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29287. * 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`.
  29288. * 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
  29289. * 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)`).
  29290. * 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
  29291. * 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.
  29292. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29293. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29295. */
  29296. Mesh.CreatePolyhedron = function (name, options, scene) {
  29297. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29298. };
  29299. /**
  29300. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29301. * Please consider using the same method from the MeshBuilder class instead.
  29302. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29303. * 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`).
  29304. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29305. * 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.
  29306. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29307. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29308. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29309. */
  29310. Mesh.CreateIcoSphere = function (name, options, scene) {
  29311. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29312. };
  29313. /**
  29314. * Creates a decal mesh.
  29315. * Please consider using the same method from the MeshBuilder class instead.
  29316. * 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.
  29317. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29318. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29319. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29320. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29321. */
  29322. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29323. var options = {
  29324. position: position,
  29325. normal: normal,
  29326. size: size,
  29327. angle: angle
  29328. };
  29329. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29330. };
  29331. // Skeletons
  29332. /**
  29333. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29334. */
  29335. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29336. if (!this._sourcePositions) {
  29337. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29338. if (!source) {
  29339. return this._sourcePositions;
  29340. }
  29341. this._sourcePositions = new Float32Array(source);
  29342. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29343. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29344. }
  29345. }
  29346. return this._sourcePositions;
  29347. };
  29348. /**
  29349. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29350. */
  29351. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29352. if (!this._sourceNormals) {
  29353. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29354. if (!source) {
  29355. return this._sourceNormals;
  29356. }
  29357. this._sourceNormals = new Float32Array(source);
  29358. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29359. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29360. }
  29361. }
  29362. return this._sourceNormals;
  29363. };
  29364. /**
  29365. * Updates the vertex buffer by applying transformation from the bones.
  29366. * Returns the Mesh.
  29367. *
  29368. * @param {skeleton} skeleton to apply
  29369. */
  29370. Mesh.prototype.applySkeleton = function (skeleton) {
  29371. if (!this.geometry) {
  29372. return this;
  29373. }
  29374. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29375. return this;
  29376. }
  29377. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29378. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29379. return this;
  29380. }
  29381. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29382. return this;
  29383. }
  29384. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29385. return this;
  29386. }
  29387. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29388. return this;
  29389. }
  29390. if (!this._sourcePositions) {
  29391. var submeshes = this.subMeshes.slice();
  29392. this.setPositionsForCPUSkinning();
  29393. this.subMeshes = submeshes;
  29394. }
  29395. if (!this._sourceNormals) {
  29396. this.setNormalsForCPUSkinning();
  29397. }
  29398. // positionsData checks for not being Float32Array will only pass at most once
  29399. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29400. if (!positionsData) {
  29401. return this;
  29402. }
  29403. if (!(positionsData instanceof Float32Array)) {
  29404. positionsData = new Float32Array(positionsData);
  29405. }
  29406. // normalsData checks for not being Float32Array will only pass at most once
  29407. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29408. if (!normalsData) {
  29409. return this;
  29410. }
  29411. if (!(normalsData instanceof Float32Array)) {
  29412. normalsData = new Float32Array(normalsData);
  29413. }
  29414. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29415. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29416. if (!matricesWeightsData || !matricesIndicesData) {
  29417. return this;
  29418. }
  29419. var needExtras = this.numBoneInfluencers > 4;
  29420. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29421. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29422. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29423. var tempVector3 = BABYLON.Vector3.Zero();
  29424. var finalMatrix = new BABYLON.Matrix();
  29425. var tempMatrix = new BABYLON.Matrix();
  29426. var matWeightIdx = 0;
  29427. var inf;
  29428. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29429. var weight;
  29430. for (inf = 0; inf < 4; inf++) {
  29431. weight = matricesWeightsData[matWeightIdx + inf];
  29432. if (weight > 0) {
  29433. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29434. finalMatrix.addToSelf(tempMatrix);
  29435. }
  29436. else
  29437. break;
  29438. }
  29439. if (needExtras) {
  29440. for (inf = 0; inf < 4; inf++) {
  29441. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29442. if (weight > 0) {
  29443. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29444. finalMatrix.addToSelf(tempMatrix);
  29445. }
  29446. else
  29447. break;
  29448. }
  29449. }
  29450. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29451. tempVector3.toArray(positionsData, index);
  29452. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29453. tempVector3.toArray(normalsData, index);
  29454. finalMatrix.reset();
  29455. }
  29456. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29457. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29458. return this;
  29459. };
  29460. // Tools
  29461. /**
  29462. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29463. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29464. */
  29465. Mesh.MinMax = function (meshes) {
  29466. var minVector = null;
  29467. var maxVector = null;
  29468. meshes.forEach(function (mesh, index, array) {
  29469. var boundingInfo = mesh.getBoundingInfo();
  29470. var boundingBox = boundingInfo.boundingBox;
  29471. if (!minVector || !maxVector) {
  29472. minVector = boundingBox.minimumWorld;
  29473. maxVector = boundingBox.maximumWorld;
  29474. }
  29475. else {
  29476. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29477. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29478. }
  29479. });
  29480. if (!minVector || !maxVector) {
  29481. return {
  29482. min: BABYLON.Vector3.Zero(),
  29483. max: BABYLON.Vector3.Zero()
  29484. };
  29485. }
  29486. return {
  29487. min: minVector,
  29488. max: maxVector
  29489. };
  29490. };
  29491. /**
  29492. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29493. */
  29494. Mesh.Center = function (meshesOrMinMaxVector) {
  29495. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29496. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29497. };
  29498. /**
  29499. * Merge the array of meshes into a single mesh for performance reasons.
  29500. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29501. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29502. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29503. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29504. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29505. */
  29506. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29507. if (disposeSource === void 0) { disposeSource = true; }
  29508. var index;
  29509. if (!allow32BitsIndices) {
  29510. var totalVertices = 0;
  29511. // Counting vertices
  29512. for (index = 0; index < meshes.length; index++) {
  29513. if (meshes[index]) {
  29514. totalVertices += meshes[index].getTotalVertices();
  29515. if (totalVertices > 65536) {
  29516. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29517. return null;
  29518. }
  29519. }
  29520. }
  29521. }
  29522. // Merge
  29523. var vertexData = null;
  29524. var otherVertexData;
  29525. var indiceArray = new Array();
  29526. var source = null;
  29527. for (index = 0; index < meshes.length; index++) {
  29528. if (meshes[index]) {
  29529. meshes[index].computeWorldMatrix(true);
  29530. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29531. otherVertexData.transform(meshes[index].getWorldMatrix());
  29532. if (vertexData) {
  29533. vertexData.merge(otherVertexData);
  29534. }
  29535. else {
  29536. vertexData = otherVertexData;
  29537. source = meshes[index];
  29538. }
  29539. if (subdivideWithSubMeshes) {
  29540. indiceArray.push(meshes[index].getTotalIndices());
  29541. }
  29542. }
  29543. }
  29544. source = source;
  29545. if (!meshSubclass) {
  29546. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29547. }
  29548. vertexData.applyToMesh(meshSubclass);
  29549. // Setting properties
  29550. meshSubclass.material = source.material;
  29551. meshSubclass.checkCollisions = source.checkCollisions;
  29552. // Cleaning
  29553. if (disposeSource) {
  29554. for (index = 0; index < meshes.length; index++) {
  29555. if (meshes[index]) {
  29556. meshes[index].dispose();
  29557. }
  29558. }
  29559. }
  29560. // Subdivide
  29561. if (subdivideWithSubMeshes) {
  29562. //-- Suppresions du submesh global
  29563. meshSubclass.releaseSubMeshes();
  29564. index = 0;
  29565. var offset = 0;
  29566. //-- aplique la subdivision en fonction du tableau d'indices
  29567. while (index < indiceArray.length) {
  29568. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29569. offset += indiceArray[index];
  29570. index++;
  29571. }
  29572. }
  29573. return meshSubclass;
  29574. };
  29575. // Consts
  29576. Mesh._FRONTSIDE = 0;
  29577. Mesh._BACKSIDE = 1;
  29578. Mesh._DOUBLESIDE = 2;
  29579. Mesh._DEFAULTSIDE = 0;
  29580. Mesh._NO_CAP = 0;
  29581. Mesh._CAP_START = 1;
  29582. Mesh._CAP_END = 2;
  29583. Mesh._CAP_ALL = 3;
  29584. return Mesh;
  29585. }(BABYLON.AbstractMesh));
  29586. BABYLON.Mesh = Mesh;
  29587. })(BABYLON || (BABYLON = {}));
  29588. //# sourceMappingURL=babylon.mesh.js.map
  29589. var BABYLON;
  29590. (function (BABYLON) {
  29591. var BaseSubMesh = /** @class */ (function () {
  29592. function BaseSubMesh() {
  29593. }
  29594. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29595. get: function () {
  29596. return this._materialEffect;
  29597. },
  29598. enumerable: true,
  29599. configurable: true
  29600. });
  29601. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29602. if (defines === void 0) { defines = null; }
  29603. if (this._materialEffect === effect) {
  29604. if (!effect) {
  29605. this._materialDefines = null;
  29606. }
  29607. return;
  29608. }
  29609. this._materialDefines = defines;
  29610. this._materialEffect = effect;
  29611. };
  29612. return BaseSubMesh;
  29613. }());
  29614. BABYLON.BaseSubMesh = BaseSubMesh;
  29615. var SubMesh = /** @class */ (function (_super) {
  29616. __extends(SubMesh, _super);
  29617. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29618. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29619. var _this = _super.call(this) || this;
  29620. _this.materialIndex = materialIndex;
  29621. _this.verticesStart = verticesStart;
  29622. _this.verticesCount = verticesCount;
  29623. _this.indexStart = indexStart;
  29624. _this.indexCount = indexCount;
  29625. _this._renderId = 0;
  29626. _this._mesh = mesh;
  29627. _this._renderingMesh = renderingMesh || mesh;
  29628. mesh.subMeshes.push(_this);
  29629. _this._trianglePlanes = [];
  29630. _this._id = mesh.subMeshes.length - 1;
  29631. if (createBoundingBox) {
  29632. _this.refreshBoundingInfo();
  29633. mesh.computeWorldMatrix(true);
  29634. }
  29635. return _this;
  29636. }
  29637. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29638. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29639. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29640. };
  29641. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29642. get: function () {
  29643. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29644. },
  29645. enumerable: true,
  29646. configurable: true
  29647. });
  29648. /**
  29649. * Returns the submesh BoudingInfo object.
  29650. */
  29651. SubMesh.prototype.getBoundingInfo = function () {
  29652. if (this.IsGlobal) {
  29653. return this._mesh.getBoundingInfo();
  29654. }
  29655. return this._boundingInfo;
  29656. };
  29657. /**
  29658. * Sets the submesh BoundingInfo.
  29659. * Return the SubMesh.
  29660. */
  29661. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  29662. this._boundingInfo = boundingInfo;
  29663. return this;
  29664. };
  29665. /**
  29666. * Returns the mesh of the current submesh.
  29667. */
  29668. SubMesh.prototype.getMesh = function () {
  29669. return this._mesh;
  29670. };
  29671. /**
  29672. * Returns the rendering mesh of the submesh.
  29673. */
  29674. SubMesh.prototype.getRenderingMesh = function () {
  29675. return this._renderingMesh;
  29676. };
  29677. /**
  29678. * Returns the submesh material.
  29679. */
  29680. SubMesh.prototype.getMaterial = function () {
  29681. var rootMaterial = this._renderingMesh.material;
  29682. if (rootMaterial === null || rootMaterial === undefined) {
  29683. return this._mesh.getScene().defaultMaterial;
  29684. }
  29685. else if (rootMaterial.getSubMaterial) {
  29686. var multiMaterial = rootMaterial;
  29687. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  29688. if (this._currentMaterial !== effectiveMaterial) {
  29689. this._currentMaterial = effectiveMaterial;
  29690. this._materialDefines = null;
  29691. }
  29692. return effectiveMaterial;
  29693. }
  29694. return rootMaterial;
  29695. };
  29696. // Methods
  29697. /**
  29698. * Sets a new updated BoundingInfo object to the submesh.
  29699. * Returns the SubMesh.
  29700. */
  29701. SubMesh.prototype.refreshBoundingInfo = function () {
  29702. this._lastColliderWorldVertices = null;
  29703. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29704. return this;
  29705. }
  29706. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29707. if (!data) {
  29708. this._boundingInfo = this._mesh.getBoundingInfo();
  29709. return this;
  29710. }
  29711. var indices = this._renderingMesh.getIndices();
  29712. var extend;
  29713. //is this the only submesh?
  29714. if (this.indexStart === 0 && this.indexCount === indices.length) {
  29715. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29716. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29717. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29718. }
  29719. else {
  29720. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29721. }
  29722. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29723. return this;
  29724. };
  29725. SubMesh.prototype._checkCollision = function (collider) {
  29726. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29727. return boundingInfo._checkCollision(collider);
  29728. };
  29729. /**
  29730. * Updates the submesh BoundingInfo.
  29731. * Returns the Submesh.
  29732. */
  29733. SubMesh.prototype.updateBoundingInfo = function (world) {
  29734. var boundingInfo = this.getBoundingInfo();
  29735. if (!boundingInfo) {
  29736. this.refreshBoundingInfo();
  29737. boundingInfo = this.getBoundingInfo();
  29738. }
  29739. boundingInfo.update(world);
  29740. return this;
  29741. };
  29742. /**
  29743. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  29744. * Boolean returned.
  29745. */
  29746. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  29747. var boundingInfo = this.getBoundingInfo();
  29748. if (!boundingInfo) {
  29749. return false;
  29750. }
  29751. return boundingInfo.isInFrustum(frustumPlanes);
  29752. };
  29753. /**
  29754. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  29755. * Boolean returned.
  29756. */
  29757. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  29758. var boundingInfo = this.getBoundingInfo();
  29759. if (!boundingInfo) {
  29760. return false;
  29761. }
  29762. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  29763. };
  29764. /**
  29765. * Renders the submesh.
  29766. * Returns it.
  29767. */
  29768. SubMesh.prototype.render = function (enableAlphaMode) {
  29769. this._renderingMesh.render(this, enableAlphaMode);
  29770. return this;
  29771. };
  29772. /**
  29773. * Returns a new Index Buffer.
  29774. * Type returned : WebGLBuffer.
  29775. */
  29776. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  29777. if (!this._linesIndexBuffer) {
  29778. var linesIndices = [];
  29779. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29780. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  29781. }
  29782. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  29783. this.linesIndexCount = linesIndices.length;
  29784. }
  29785. return this._linesIndexBuffer;
  29786. };
  29787. /**
  29788. * True is the passed Ray intersects the submesh bounding box.
  29789. * Boolean returned.
  29790. */
  29791. SubMesh.prototype.canIntersects = function (ray) {
  29792. var boundingInfo = this.getBoundingInfo();
  29793. if (!boundingInfo) {
  29794. return false;
  29795. }
  29796. return ray.intersectsBox(boundingInfo.boundingBox);
  29797. };
  29798. /**
  29799. * Returns an object IntersectionInfo.
  29800. */
  29801. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  29802. var intersectInfo = null;
  29803. // LineMesh first as it's also a Mesh...
  29804. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  29805. var lineMesh = this._mesh;
  29806. // Line test
  29807. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  29808. var p0 = positions[indices[index]];
  29809. var p1 = positions[indices[index + 1]];
  29810. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  29811. if (length < 0) {
  29812. continue;
  29813. }
  29814. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  29815. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  29816. if (fastCheck) {
  29817. break;
  29818. }
  29819. }
  29820. }
  29821. }
  29822. else {
  29823. // Triangles test
  29824. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29825. var p0 = positions[indices[index]];
  29826. var p1 = positions[indices[index + 1]];
  29827. var p2 = positions[indices[index + 2]];
  29828. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  29829. if (currentIntersectInfo) {
  29830. if (currentIntersectInfo.distance < 0) {
  29831. continue;
  29832. }
  29833. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  29834. intersectInfo = currentIntersectInfo;
  29835. intersectInfo.faceId = index / 3;
  29836. if (fastCheck) {
  29837. break;
  29838. }
  29839. }
  29840. }
  29841. }
  29842. }
  29843. return intersectInfo;
  29844. };
  29845. SubMesh.prototype._rebuild = function () {
  29846. if (this._linesIndexBuffer) {
  29847. this._linesIndexBuffer = null;
  29848. }
  29849. };
  29850. // Clone
  29851. /**
  29852. * Creates a new Submesh from the passed Mesh.
  29853. */
  29854. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29855. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29856. if (!this.IsGlobal) {
  29857. var boundingInfo = this.getBoundingInfo();
  29858. if (!boundingInfo) {
  29859. return result;
  29860. }
  29861. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29862. }
  29863. return result;
  29864. };
  29865. // Dispose
  29866. /**
  29867. * Disposes the Submesh.
  29868. * Returns nothing.
  29869. */
  29870. SubMesh.prototype.dispose = function () {
  29871. if (this._linesIndexBuffer) {
  29872. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29873. this._linesIndexBuffer = null;
  29874. }
  29875. // Remove from mesh
  29876. var index = this._mesh.subMeshes.indexOf(this);
  29877. this._mesh.subMeshes.splice(index, 1);
  29878. };
  29879. // Statics
  29880. /**
  29881. * Creates a new Submesh from the passed parameters :
  29882. * - materialIndex (integer) : the index of the main mesh material.
  29883. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29884. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29885. * - mesh (Mesh) : the main mesh to create the submesh from.
  29886. * - renderingMesh (optional Mesh) : rendering mesh.
  29887. */
  29888. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29889. var minVertexIndex = Number.MAX_VALUE;
  29890. var maxVertexIndex = -Number.MAX_VALUE;
  29891. renderingMesh = (renderingMesh || mesh);
  29892. var indices = renderingMesh.getIndices();
  29893. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29894. var vertexIndex = indices[index];
  29895. if (vertexIndex < minVertexIndex)
  29896. minVertexIndex = vertexIndex;
  29897. if (vertexIndex > maxVertexIndex)
  29898. maxVertexIndex = vertexIndex;
  29899. }
  29900. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  29901. };
  29902. return SubMesh;
  29903. }(BaseSubMesh));
  29904. BABYLON.SubMesh = SubMesh;
  29905. })(BABYLON || (BABYLON = {}));
  29906. //# sourceMappingURL=babylon.subMesh.js.map
  29907. var __assign = (this && this.__assign) || Object.assign || function(t) {
  29908. for (var s, i = 1, n = arguments.length; i < n; i++) {
  29909. s = arguments[i];
  29910. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  29911. t[p] = s[p];
  29912. }
  29913. return t;
  29914. };
  29915. var BABYLON;
  29916. (function (BABYLON) {
  29917. /**
  29918. * Manages the defines for the Material.
  29919. */
  29920. var MaterialDefines = /** @class */ (function () {
  29921. function MaterialDefines() {
  29922. this._isDirty = true;
  29923. this._areLightsDirty = true;
  29924. this._areAttributesDirty = true;
  29925. this._areTexturesDirty = true;
  29926. this._areFresnelDirty = true;
  29927. this._areMiscDirty = true;
  29928. this._areImageProcessingDirty = true;
  29929. this._normals = false;
  29930. this._uvs = false;
  29931. this._needNormals = false;
  29932. this._needUVs = false;
  29933. }
  29934. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  29935. /**
  29936. * Specifies if the material needs to be re-calculated.
  29937. */
  29938. get: function () {
  29939. return this._isDirty;
  29940. },
  29941. enumerable: true,
  29942. configurable: true
  29943. });
  29944. /**
  29945. * Marks the material to indicate that it has been re-calculated.
  29946. */
  29947. MaterialDefines.prototype.markAsProcessed = function () {
  29948. this._isDirty = false;
  29949. this._areAttributesDirty = false;
  29950. this._areTexturesDirty = false;
  29951. this._areFresnelDirty = false;
  29952. this._areLightsDirty = false;
  29953. this._areMiscDirty = false;
  29954. this._areImageProcessingDirty = false;
  29955. };
  29956. /**
  29957. * Marks the material to indicate that it needs to be re-calculated.
  29958. */
  29959. MaterialDefines.prototype.markAsUnprocessed = function () {
  29960. this._isDirty = true;
  29961. };
  29962. /**
  29963. * Marks the material to indicate all of its defines need to be re-calculated.
  29964. */
  29965. MaterialDefines.prototype.markAllAsDirty = function () {
  29966. this._areTexturesDirty = true;
  29967. this._areAttributesDirty = true;
  29968. this._areLightsDirty = true;
  29969. this._areFresnelDirty = true;
  29970. this._areMiscDirty = true;
  29971. this._areImageProcessingDirty = true;
  29972. this._isDirty = true;
  29973. };
  29974. /**
  29975. * Marks the material to indicate that image processing needs to be re-calculated.
  29976. */
  29977. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  29978. this._areImageProcessingDirty = true;
  29979. this._isDirty = true;
  29980. };
  29981. /**
  29982. * Marks the material to indicate the lights need to be re-calculated.
  29983. */
  29984. MaterialDefines.prototype.markAsLightDirty = function () {
  29985. this._areLightsDirty = true;
  29986. this._isDirty = true;
  29987. };
  29988. /**
  29989. * Marks the attribute state as changed.
  29990. */
  29991. MaterialDefines.prototype.markAsAttributesDirty = function () {
  29992. this._areAttributesDirty = true;
  29993. this._isDirty = true;
  29994. };
  29995. /**
  29996. * Marks the texture state as changed.
  29997. */
  29998. MaterialDefines.prototype.markAsTexturesDirty = function () {
  29999. this._areTexturesDirty = true;
  30000. this._isDirty = true;
  30001. };
  30002. /**
  30003. * Marks the fresnel state as changed.
  30004. */
  30005. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30006. this._areFresnelDirty = true;
  30007. this._isDirty = true;
  30008. };
  30009. /**
  30010. * Marks the misc state as changed.
  30011. */
  30012. MaterialDefines.prototype.markAsMiscDirty = function () {
  30013. this._areMiscDirty = true;
  30014. this._isDirty = true;
  30015. };
  30016. /**
  30017. * Rebuilds the material defines.
  30018. */
  30019. MaterialDefines.prototype.rebuild = function () {
  30020. if (this._keys) {
  30021. delete this._keys;
  30022. }
  30023. this._keys = [];
  30024. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30025. var key = _a[_i];
  30026. if (key[0] === "_") {
  30027. continue;
  30028. }
  30029. this._keys.push(key);
  30030. }
  30031. };
  30032. /**
  30033. * Specifies if two material defines are equal.
  30034. * @param other - A material define instance to compare to.
  30035. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30036. */
  30037. MaterialDefines.prototype.isEqual = function (other) {
  30038. if (this._keys.length !== other._keys.length) {
  30039. return false;
  30040. }
  30041. for (var index = 0; index < this._keys.length; index++) {
  30042. var prop = this._keys[index];
  30043. if (this[prop] !== other[prop]) {
  30044. return false;
  30045. }
  30046. }
  30047. return true;
  30048. };
  30049. /**
  30050. * Clones this instance's defines to another instance.
  30051. * @param other - material defines to clone values to.
  30052. */
  30053. MaterialDefines.prototype.cloneTo = function (other) {
  30054. if (this._keys.length !== other._keys.length) {
  30055. other._keys = this._keys.slice(0);
  30056. }
  30057. for (var index = 0; index < this._keys.length; index++) {
  30058. var prop = this._keys[index];
  30059. other[prop] = this[prop];
  30060. }
  30061. };
  30062. /**
  30063. * Resets the material define values.
  30064. */
  30065. MaterialDefines.prototype.reset = function () {
  30066. for (var index = 0; index < this._keys.length; index++) {
  30067. var prop = this._keys[index];
  30068. if (typeof (this[prop]) === "number") {
  30069. this[prop] = 0;
  30070. }
  30071. else {
  30072. this[prop] = false;
  30073. }
  30074. }
  30075. };
  30076. /**
  30077. * Converts the material define values to a string.
  30078. * @returns - String of material define information.
  30079. */
  30080. MaterialDefines.prototype.toString = function () {
  30081. var result = "";
  30082. for (var index = 0; index < this._keys.length; index++) {
  30083. var prop = this._keys[index];
  30084. var value = this[prop];
  30085. if (typeof (value) === "number") {
  30086. result += "#define " + prop + " " + this[prop] + "\n";
  30087. }
  30088. else if (value) {
  30089. result += "#define " + prop + "\n";
  30090. }
  30091. }
  30092. return result;
  30093. };
  30094. return MaterialDefines;
  30095. }());
  30096. BABYLON.MaterialDefines = MaterialDefines;
  30097. /**
  30098. * This offers the main features of a material in BJS.
  30099. */
  30100. var Material = /** @class */ (function () {
  30101. /**
  30102. * Creates a material instance.
  30103. * @param name - The name of the material.
  30104. * @param scene - The BJS scene to reference.
  30105. * @param doNotAdd - Specifies if the material should be added to the scene.
  30106. */
  30107. function Material(name, scene, doNotAdd) {
  30108. /**
  30109. * Specifies if the ready state should be checked on each call.
  30110. */
  30111. this.checkReadyOnEveryCall = false;
  30112. /**
  30113. * Specifies if the ready state should be checked once.
  30114. */
  30115. this.checkReadyOnlyOnce = false;
  30116. /**
  30117. * The state of the material.
  30118. */
  30119. this.state = "";
  30120. /**
  30121. * The alpha value of the material.
  30122. */
  30123. this._alpha = 1.0;
  30124. /**
  30125. * Specifies if back face culling is enabled.
  30126. */
  30127. this._backFaceCulling = true;
  30128. /**
  30129. * Specifies if the material should be serialized.
  30130. */
  30131. this.doNotSerialize = false;
  30132. /**
  30133. * Specifies if the effect should be stored on sub meshes.
  30134. */
  30135. this.storeEffectOnSubMeshes = false;
  30136. /**
  30137. * An event triggered when the material is disposed.
  30138. * @type {BABYLON.Observable}
  30139. */
  30140. this.onDisposeObservable = new BABYLON.Observable();
  30141. /**
  30142. * An event triggered when the material is bound.
  30143. * @type {BABYLON.Observable}
  30144. */
  30145. this.onBindObservable = new BABYLON.Observable();
  30146. /**
  30147. * An event triggered when the material is unbound.
  30148. * @type {BABYLON.Observable}
  30149. */
  30150. this.onUnBindObservable = new BABYLON.Observable();
  30151. /**
  30152. * Stores the value of the alpha mode.
  30153. */
  30154. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30155. /**
  30156. * Stores the state of the need depth pre-pass value.
  30157. */
  30158. this._needDepthPrePass = false;
  30159. /**
  30160. * Specifies if depth writing should be disabled.
  30161. */
  30162. this.disableDepthWrite = false;
  30163. /**
  30164. * Specifies if depth writing should be forced.
  30165. */
  30166. this.forceDepthWrite = false;
  30167. /**
  30168. * Specifies if there should be a separate pass for culling.
  30169. */
  30170. this.separateCullingPass = false;
  30171. /**
  30172. * Stores the state specifing if fog should be enabled.
  30173. */
  30174. this._fogEnabled = true;
  30175. /**
  30176. * Stores the size of points.
  30177. */
  30178. this.pointSize = 1.0;
  30179. /**
  30180. * Stores the z offset value.
  30181. */
  30182. this.zOffset = 0;
  30183. /**
  30184. * Specifies if the material was previously ready.
  30185. */
  30186. this._wasPreviouslyReady = false;
  30187. /**
  30188. * Stores the fill mode state.
  30189. */
  30190. this._fillMode = Material.TriangleFillMode;
  30191. this.name = name;
  30192. this.id = name || BABYLON.Tools.RandomId();
  30193. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30194. if (this._scene.useRightHandedSystem) {
  30195. this.sideOrientation = Material.ClockWiseSideOrientation;
  30196. }
  30197. else {
  30198. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30199. }
  30200. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30201. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30202. if (!doNotAdd) {
  30203. this._scene.materials.push(this);
  30204. }
  30205. }
  30206. Object.defineProperty(Material, "TriangleFillMode", {
  30207. /**
  30208. * Returns the triangle fill mode.
  30209. */
  30210. get: function () {
  30211. return Material._TriangleFillMode;
  30212. },
  30213. enumerable: true,
  30214. configurable: true
  30215. });
  30216. Object.defineProperty(Material, "WireFrameFillMode", {
  30217. /**
  30218. * Returns the wireframe mode.
  30219. */
  30220. get: function () {
  30221. return Material._WireFrameFillMode;
  30222. },
  30223. enumerable: true,
  30224. configurable: true
  30225. });
  30226. Object.defineProperty(Material, "PointFillMode", {
  30227. /**
  30228. * Returns the point fill mode.
  30229. */
  30230. get: function () {
  30231. return Material._PointFillMode;
  30232. },
  30233. enumerable: true,
  30234. configurable: true
  30235. });
  30236. Object.defineProperty(Material, "PointListDrawMode", {
  30237. /**
  30238. * Returns the point list draw mode.
  30239. */
  30240. get: function () {
  30241. return Material._PointListDrawMode;
  30242. },
  30243. enumerable: true,
  30244. configurable: true
  30245. });
  30246. Object.defineProperty(Material, "LineListDrawMode", {
  30247. /**
  30248. * Returns the line list draw mode.
  30249. */
  30250. get: function () {
  30251. return Material._LineListDrawMode;
  30252. },
  30253. enumerable: true,
  30254. configurable: true
  30255. });
  30256. Object.defineProperty(Material, "LineLoopDrawMode", {
  30257. /**
  30258. * Returns the line loop draw mode.
  30259. */
  30260. get: function () {
  30261. return Material._LineLoopDrawMode;
  30262. },
  30263. enumerable: true,
  30264. configurable: true
  30265. });
  30266. Object.defineProperty(Material, "LineStripDrawMode", {
  30267. /**
  30268. * Returns the line strip draw mode.
  30269. */
  30270. get: function () {
  30271. return Material._LineStripDrawMode;
  30272. },
  30273. enumerable: true,
  30274. configurable: true
  30275. });
  30276. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30277. /**
  30278. * Returns the triangle strip draw mode.
  30279. */
  30280. get: function () {
  30281. return Material._TriangleStripDrawMode;
  30282. },
  30283. enumerable: true,
  30284. configurable: true
  30285. });
  30286. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30287. /**
  30288. * Returns the triangle fan draw mode.
  30289. */
  30290. get: function () {
  30291. return Material._TriangleFanDrawMode;
  30292. },
  30293. enumerable: true,
  30294. configurable: true
  30295. });
  30296. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30297. /**
  30298. * Returns the clock-wise side orientation.
  30299. */
  30300. get: function () {
  30301. return Material._ClockWiseSideOrientation;
  30302. },
  30303. enumerable: true,
  30304. configurable: true
  30305. });
  30306. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30307. /**
  30308. * Returns the counter clock-wise side orientation.
  30309. */
  30310. get: function () {
  30311. return Material._CounterClockWiseSideOrientation;
  30312. },
  30313. enumerable: true,
  30314. configurable: true
  30315. });
  30316. Object.defineProperty(Material, "TextureDirtyFlag", {
  30317. /**
  30318. * Returns the dirty texture flag value.
  30319. */
  30320. get: function () {
  30321. return Material._TextureDirtyFlag;
  30322. },
  30323. enumerable: true,
  30324. configurable: true
  30325. });
  30326. Object.defineProperty(Material, "LightDirtyFlag", {
  30327. /**
  30328. * Returns the dirty light flag value.
  30329. */
  30330. get: function () {
  30331. return Material._LightDirtyFlag;
  30332. },
  30333. enumerable: true,
  30334. configurable: true
  30335. });
  30336. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30337. /**
  30338. * Returns the dirty fresnel flag value.
  30339. */
  30340. get: function () {
  30341. return Material._FresnelDirtyFlag;
  30342. },
  30343. enumerable: true,
  30344. configurable: true
  30345. });
  30346. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30347. /**
  30348. * Returns the dirty attributes flag value.
  30349. */
  30350. get: function () {
  30351. return Material._AttributesDirtyFlag;
  30352. },
  30353. enumerable: true,
  30354. configurable: true
  30355. });
  30356. Object.defineProperty(Material, "MiscDirtyFlag", {
  30357. /**
  30358. * Returns the dirty misc flag value.
  30359. */
  30360. get: function () {
  30361. return Material._MiscDirtyFlag;
  30362. },
  30363. enumerable: true,
  30364. configurable: true
  30365. });
  30366. Object.defineProperty(Material.prototype, "alpha", {
  30367. /**
  30368. * Gets the alpha value of the material.
  30369. */
  30370. get: function () {
  30371. return this._alpha;
  30372. },
  30373. /**
  30374. * Sets the alpha value of the material.
  30375. */
  30376. set: function (value) {
  30377. if (this._alpha === value) {
  30378. return;
  30379. }
  30380. this._alpha = value;
  30381. this.markAsDirty(Material.MiscDirtyFlag);
  30382. },
  30383. enumerable: true,
  30384. configurable: true
  30385. });
  30386. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30387. /**
  30388. * Gets the back-face culling state.
  30389. */
  30390. get: function () {
  30391. return this._backFaceCulling;
  30392. },
  30393. /**
  30394. * Sets the back-face culling state.
  30395. */
  30396. set: function (value) {
  30397. if (this._backFaceCulling === value) {
  30398. return;
  30399. }
  30400. this._backFaceCulling = value;
  30401. this.markAsDirty(Material.TextureDirtyFlag);
  30402. },
  30403. enumerable: true,
  30404. configurable: true
  30405. });
  30406. Object.defineProperty(Material.prototype, "onDispose", {
  30407. /**
  30408. * Called during a dispose event.
  30409. */
  30410. set: function (callback) {
  30411. if (this._onDisposeObserver) {
  30412. this.onDisposeObservable.remove(this._onDisposeObserver);
  30413. }
  30414. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30415. },
  30416. enumerable: true,
  30417. configurable: true
  30418. });
  30419. Object.defineProperty(Material.prototype, "onBind", {
  30420. /**
  30421. * Called during a bind event.
  30422. */
  30423. set: function (callback) {
  30424. if (this._onBindObserver) {
  30425. this.onBindObservable.remove(this._onBindObserver);
  30426. }
  30427. this._onBindObserver = this.onBindObservable.add(callback);
  30428. },
  30429. enumerable: true,
  30430. configurable: true
  30431. });
  30432. Object.defineProperty(Material.prototype, "alphaMode", {
  30433. /**
  30434. * Gets the value of the alpha mode.
  30435. */
  30436. get: function () {
  30437. return this._alphaMode;
  30438. },
  30439. /**
  30440. * Sets the value of the alpha mode.
  30441. */
  30442. set: function (value) {
  30443. if (this._alphaMode === value) {
  30444. return;
  30445. }
  30446. this._alphaMode = value;
  30447. this.markAsDirty(Material.TextureDirtyFlag);
  30448. },
  30449. enumerable: true,
  30450. configurable: true
  30451. });
  30452. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30453. /**
  30454. * Gets the depth pre-pass value.
  30455. */
  30456. get: function () {
  30457. return this._needDepthPrePass;
  30458. },
  30459. /**
  30460. * Sets the need depth pre-pass value.
  30461. */
  30462. set: function (value) {
  30463. if (this._needDepthPrePass === value) {
  30464. return;
  30465. }
  30466. this._needDepthPrePass = value;
  30467. if (this._needDepthPrePass) {
  30468. this.checkReadyOnEveryCall = true;
  30469. }
  30470. },
  30471. enumerable: true,
  30472. configurable: true
  30473. });
  30474. Object.defineProperty(Material.prototype, "fogEnabled", {
  30475. /**
  30476. * Gets the value of the fog enabled state.
  30477. */
  30478. get: function () {
  30479. return this._fogEnabled;
  30480. },
  30481. /**
  30482. * Sets the state for enabling fog.
  30483. */
  30484. set: function (value) {
  30485. if (this._fogEnabled === value) {
  30486. return;
  30487. }
  30488. this._fogEnabled = value;
  30489. this.markAsDirty(Material.MiscDirtyFlag);
  30490. },
  30491. enumerable: true,
  30492. configurable: true
  30493. });
  30494. Object.defineProperty(Material.prototype, "wireframe", {
  30495. /**
  30496. * Gets a value specifying if wireframe mode is enabled.
  30497. */
  30498. get: function () {
  30499. return this._fillMode === Material.WireFrameFillMode;
  30500. },
  30501. /**
  30502. * Sets the state of wireframe mode.
  30503. */
  30504. set: function (value) {
  30505. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30506. },
  30507. enumerable: true,
  30508. configurable: true
  30509. });
  30510. Object.defineProperty(Material.prototype, "pointsCloud", {
  30511. /**
  30512. * Gets the value specifying if point clouds are enabled.
  30513. */
  30514. get: function () {
  30515. return this._fillMode === Material.PointFillMode;
  30516. },
  30517. /**
  30518. * Sets the state of point cloud mode.
  30519. */
  30520. set: function (value) {
  30521. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30522. },
  30523. enumerable: true,
  30524. configurable: true
  30525. });
  30526. Object.defineProperty(Material.prototype, "fillMode", {
  30527. /**
  30528. * Gets the material fill mode.
  30529. */
  30530. get: function () {
  30531. return this._fillMode;
  30532. },
  30533. /**
  30534. * Sets the material fill mode.
  30535. */
  30536. set: function (value) {
  30537. if (this._fillMode === value) {
  30538. return;
  30539. }
  30540. this._fillMode = value;
  30541. this.markAsDirty(Material.MiscDirtyFlag);
  30542. },
  30543. enumerable: true,
  30544. configurable: true
  30545. });
  30546. /**
  30547. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30548. * subclasses should override adding information pertainent to themselves.
  30549. * @returns - String with material information.
  30550. */
  30551. Material.prototype.toString = function (fullDetails) {
  30552. var ret = "Name: " + this.name;
  30553. if (fullDetails) {
  30554. }
  30555. return ret;
  30556. };
  30557. /**
  30558. * Gets the class name of the material.
  30559. * @returns - String with the class name of the material.
  30560. */
  30561. Material.prototype.getClassName = function () {
  30562. return "Material";
  30563. };
  30564. Object.defineProperty(Material.prototype, "isFrozen", {
  30565. /**
  30566. * Specifies if updates for the material been locked.
  30567. */
  30568. get: function () {
  30569. return this.checkReadyOnlyOnce;
  30570. },
  30571. enumerable: true,
  30572. configurable: true
  30573. });
  30574. /**
  30575. * Locks updates for the material.
  30576. */
  30577. Material.prototype.freeze = function () {
  30578. this.checkReadyOnlyOnce = true;
  30579. };
  30580. /**
  30581. * Unlocks updates for the material.
  30582. */
  30583. Material.prototype.unfreeze = function () {
  30584. this.checkReadyOnlyOnce = false;
  30585. };
  30586. /**
  30587. * Specifies if the material is ready to be used.
  30588. * @param mesh - BJS mesh.
  30589. * @param useInstances - Specifies if instances should be used.
  30590. * @returns - Boolean indicating if the material is ready to be used.
  30591. */
  30592. Material.prototype.isReady = function (mesh, useInstances) {
  30593. return true;
  30594. };
  30595. /**
  30596. * Specifies that the submesh is ready to be used.
  30597. * @param mesh - BJS mesh.
  30598. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30599. * @param useInstances - Specifies that instances should be used.
  30600. * @returns - boolean indicating that the submesh is ready or not.
  30601. */
  30602. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30603. return false;
  30604. };
  30605. /**
  30606. * Returns the material effect.
  30607. * @returns - Nullable material effect.
  30608. */
  30609. Material.prototype.getEffect = function () {
  30610. return this._effect;
  30611. };
  30612. /**
  30613. * Returns the BJS scene.
  30614. * @returns - BJS Scene.
  30615. */
  30616. Material.prototype.getScene = function () {
  30617. return this._scene;
  30618. };
  30619. /**
  30620. * Specifies if the material will require alpha blending
  30621. * @returns - Boolean specifying if alpha blending is needed.
  30622. */
  30623. Material.prototype.needAlphaBlending = function () {
  30624. return (this.alpha < 1.0);
  30625. };
  30626. /**
  30627. * Specifies if the mesh will require alpha blending.
  30628. * @param mesh - BJS mesh.
  30629. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30630. */
  30631. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30632. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30633. };
  30634. /**
  30635. * Specifies if this material should be rendered in alpha test mode.
  30636. * @returns - Boolean specifying if an alpha test is needed.
  30637. */
  30638. Material.prototype.needAlphaTesting = function () {
  30639. return false;
  30640. };
  30641. /**
  30642. * Gets the texture used for the alpha test.
  30643. * @returns - Nullable alpha test texture.
  30644. */
  30645. Material.prototype.getAlphaTestTexture = function () {
  30646. return null;
  30647. };
  30648. /**
  30649. * Marks the material to indicate that it needs to be re-calculated.
  30650. */
  30651. Material.prototype.markDirty = function () {
  30652. this._wasPreviouslyReady = false;
  30653. };
  30654. Material.prototype._preBind = function (effect, overrideOrientation) {
  30655. if (overrideOrientation === void 0) { overrideOrientation = null; }
  30656. var engine = this._scene.getEngine();
  30657. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  30658. var reverse = orientation === Material.ClockWiseSideOrientation;
  30659. engine.enableEffect(effect ? effect : this._effect);
  30660. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30661. return reverse;
  30662. };
  30663. /**
  30664. * Binds the material to the mesh.
  30665. * @param world - World transformation matrix.
  30666. * @param mesh - Mesh to bind the material to.
  30667. */
  30668. Material.prototype.bind = function (world, mesh) {
  30669. };
  30670. /**
  30671. * Binds the submesh to the material.
  30672. * @param world - World transformation matrix.
  30673. * @param mesh - Mesh containing the submesh.
  30674. * @param subMesh - Submesh to bind the material to.
  30675. */
  30676. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30677. };
  30678. /**
  30679. * Binds the world matrix to the material.
  30680. * @param world - World transformation matrix.
  30681. */
  30682. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30683. };
  30684. /**
  30685. * Binds the scene's uniform buffer to the effect.
  30686. * @param effect - Effect to bind to the scene uniform buffer.
  30687. * @param sceneUbo - Scene uniform buffer.
  30688. */
  30689. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  30690. sceneUbo.bindToEffect(effect, "Scene");
  30691. };
  30692. /**
  30693. * Binds the view matrix to the effect.
  30694. * @param effect - Effect to bind the view matrix to.
  30695. */
  30696. Material.prototype.bindView = function (effect) {
  30697. if (!this._useUBO) {
  30698. effect.setMatrix("view", this.getScene().getViewMatrix());
  30699. }
  30700. else {
  30701. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30702. }
  30703. };
  30704. /**
  30705. * Binds the view projection matrix to the effect.
  30706. * @param effect - Effect to bind the view projection matrix to.
  30707. */
  30708. Material.prototype.bindViewProjection = function (effect) {
  30709. if (!this._useUBO) {
  30710. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30711. }
  30712. else {
  30713. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30714. }
  30715. };
  30716. /**
  30717. * Specifies if material alpha testing should be turned on for the mesh.
  30718. * @param mesh - BJS mesh.
  30719. */
  30720. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  30721. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  30722. };
  30723. /**
  30724. * Processes to execute after binding the material to a mesh.
  30725. * @param mesh - BJS mesh.
  30726. */
  30727. Material.prototype._afterBind = function (mesh) {
  30728. this._scene._cachedMaterial = this;
  30729. if (mesh) {
  30730. this._scene._cachedVisibility = mesh.visibility;
  30731. }
  30732. else {
  30733. this._scene._cachedVisibility = 1;
  30734. }
  30735. if (mesh) {
  30736. this.onBindObservable.notifyObservers(mesh);
  30737. }
  30738. if (this.disableDepthWrite) {
  30739. var engine = this._scene.getEngine();
  30740. this._cachedDepthWriteState = engine.getDepthWrite();
  30741. engine.setDepthWrite(false);
  30742. }
  30743. };
  30744. /**
  30745. * Unbinds the material from the mesh.
  30746. */
  30747. Material.prototype.unbind = function () {
  30748. this.onUnBindObservable.notifyObservers(this);
  30749. if (this.disableDepthWrite) {
  30750. var engine = this._scene.getEngine();
  30751. engine.setDepthWrite(this._cachedDepthWriteState);
  30752. }
  30753. };
  30754. /**
  30755. * Gets the active textures from the material.
  30756. * @returns - Array of textures.
  30757. */
  30758. Material.prototype.getActiveTextures = function () {
  30759. return [];
  30760. };
  30761. /**
  30762. * Specifies if the material uses a texture.
  30763. * @param texture - Texture to check against the material.
  30764. * @returns - Boolean specifying if the material uses the texture.
  30765. */
  30766. Material.prototype.hasTexture = function (texture) {
  30767. return false;
  30768. };
  30769. /**
  30770. * Makes a duplicate of the material, and gives it a new name.
  30771. * @param name - Name to call the duplicated material.
  30772. * @returns - Nullable cloned material
  30773. */
  30774. Material.prototype.clone = function (name) {
  30775. return null;
  30776. };
  30777. /**
  30778. * Gets the meshes bound to the material.
  30779. * @returns - Array of meshes bound to the material.
  30780. */
  30781. Material.prototype.getBindedMeshes = function () {
  30782. var result = new Array();
  30783. for (var index = 0; index < this._scene.meshes.length; index++) {
  30784. var mesh = this._scene.meshes[index];
  30785. if (mesh.material === this) {
  30786. result.push(mesh);
  30787. }
  30788. }
  30789. return result;
  30790. };
  30791. /**
  30792. * Force shader compilation
  30793. * @param mesh - BJS mesh.
  30794. * @param onCompiled - function to execute once the material is compiled.
  30795. * @param options - options to pass to this function.
  30796. */
  30797. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  30798. var _this = this;
  30799. var localOptions = __assign({ clipPlane: false }, options);
  30800. var subMesh = new BABYLON.BaseSubMesh();
  30801. var scene = this.getScene();
  30802. var checkReady = function () {
  30803. if (!_this._scene || !_this._scene.getEngine()) {
  30804. return;
  30805. }
  30806. if (subMesh._materialDefines) {
  30807. subMesh._materialDefines._renderId = -1;
  30808. }
  30809. var clipPlaneState = scene.clipPlane;
  30810. if (localOptions.clipPlane) {
  30811. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  30812. }
  30813. if (_this.storeEffectOnSubMeshes) {
  30814. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  30815. if (onCompiled) {
  30816. onCompiled(_this);
  30817. }
  30818. }
  30819. else {
  30820. setTimeout(checkReady, 16);
  30821. }
  30822. }
  30823. else {
  30824. if (_this.isReady(mesh)) {
  30825. if (onCompiled) {
  30826. onCompiled(_this);
  30827. }
  30828. }
  30829. else {
  30830. setTimeout(checkReady, 16);
  30831. }
  30832. }
  30833. if (localOptions.clipPlane) {
  30834. scene.clipPlane = clipPlaneState;
  30835. }
  30836. };
  30837. checkReady();
  30838. };
  30839. /**
  30840. * Force shader compilation.
  30841. * @param mesh The mesh that will use this material
  30842. * @param options Additional options for compiling the shaders
  30843. * @returns A promise that resolves when the compilation completes
  30844. */
  30845. Material.prototype.forceCompilationAsync = function (mesh, options) {
  30846. var _this = this;
  30847. return new Promise(function (resolve) {
  30848. _this.forceCompilation(mesh, function () {
  30849. resolve();
  30850. }, options);
  30851. });
  30852. };
  30853. /**
  30854. * Marks a define in the material to indicate that it needs to be re-computed.
  30855. * @param flag - Material define flag.
  30856. */
  30857. Material.prototype.markAsDirty = function (flag) {
  30858. if (flag & Material.TextureDirtyFlag) {
  30859. this._markAllSubMeshesAsTexturesDirty();
  30860. }
  30861. if (flag & Material.LightDirtyFlag) {
  30862. this._markAllSubMeshesAsLightsDirty();
  30863. }
  30864. if (flag & Material.FresnelDirtyFlag) {
  30865. this._markAllSubMeshesAsFresnelDirty();
  30866. }
  30867. if (flag & Material.AttributesDirtyFlag) {
  30868. this._markAllSubMeshesAsAttributesDirty();
  30869. }
  30870. if (flag & Material.MiscDirtyFlag) {
  30871. this._markAllSubMeshesAsMiscDirty();
  30872. }
  30873. this.getScene().resetCachedMaterial();
  30874. };
  30875. /**
  30876. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  30877. * @param func - function which checks material defines against the submeshes.
  30878. */
  30879. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  30880. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  30881. var mesh = _a[_i];
  30882. if (!mesh.subMeshes) {
  30883. continue;
  30884. }
  30885. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  30886. var subMesh = _c[_b];
  30887. if (subMesh.getMaterial() !== this) {
  30888. continue;
  30889. }
  30890. if (!subMesh._materialDefines) {
  30891. continue;
  30892. }
  30893. func(subMesh._materialDefines);
  30894. }
  30895. }
  30896. };
  30897. /**
  30898. * Indicates that image processing needs to be re-calculated for all submeshes.
  30899. */
  30900. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  30901. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  30902. };
  30903. /**
  30904. * Indicates that textures need to be re-calculated for all submeshes.
  30905. */
  30906. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  30907. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  30908. };
  30909. /**
  30910. * Indicates that fresnel needs to be re-calculated for all submeshes.
  30911. */
  30912. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  30913. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  30914. };
  30915. /**
  30916. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  30917. */
  30918. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  30919. this._markAllSubMeshesAsDirty(function (defines) {
  30920. defines.markAsFresnelDirty();
  30921. defines.markAsMiscDirty();
  30922. });
  30923. };
  30924. /**
  30925. * Indicates that lights need to be re-calculated for all submeshes.
  30926. */
  30927. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  30928. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  30929. };
  30930. /**
  30931. * Indicates that attributes need to be re-calculated for all submeshes.
  30932. */
  30933. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  30934. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  30935. };
  30936. /**
  30937. * Indicates that misc needs to be re-calculated for all submeshes.
  30938. */
  30939. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  30940. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  30941. };
  30942. /**
  30943. * Indicates that textures and misc need to be re-calculated for all submeshes.
  30944. */
  30945. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  30946. this._markAllSubMeshesAsDirty(function (defines) {
  30947. defines.markAsTexturesDirty();
  30948. defines.markAsMiscDirty();
  30949. });
  30950. };
  30951. /**
  30952. * Disposes the material.
  30953. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  30954. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  30955. */
  30956. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30957. // Animations
  30958. this.getScene().stopAnimation(this);
  30959. // Remove from scene
  30960. var index = this._scene.materials.indexOf(this);
  30961. if (index >= 0) {
  30962. this._scene.materials.splice(index, 1);
  30963. }
  30964. // Remove from meshes
  30965. for (index = 0; index < this._scene.meshes.length; index++) {
  30966. var mesh = this._scene.meshes[index];
  30967. if (mesh.material === this) {
  30968. mesh.material = null;
  30969. if (mesh.geometry) {
  30970. var geometry = (mesh.geometry);
  30971. if (this.storeEffectOnSubMeshes) {
  30972. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  30973. var subMesh = _a[_i];
  30974. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  30975. if (forceDisposeEffect && subMesh._materialEffect) {
  30976. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  30977. }
  30978. }
  30979. }
  30980. else {
  30981. geometry._releaseVertexArrayObject(this._effect);
  30982. }
  30983. }
  30984. }
  30985. }
  30986. this._uniformBuffer.dispose();
  30987. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  30988. if (forceDisposeEffect && this._effect) {
  30989. if (!this.storeEffectOnSubMeshes) {
  30990. this._scene.getEngine()._releaseEffect(this._effect);
  30991. }
  30992. this._effect = null;
  30993. }
  30994. // Callback
  30995. this.onDisposeObservable.notifyObservers(this);
  30996. this.onDisposeObservable.clear();
  30997. this.onBindObservable.clear();
  30998. this.onUnBindObservable.clear();
  30999. };
  31000. /**
  31001. * Serializes this material.
  31002. * @returns - serialized material object.
  31003. */
  31004. Material.prototype.serialize = function () {
  31005. return BABYLON.SerializationHelper.Serialize(this);
  31006. };
  31007. /**
  31008. * Creates a MultiMaterial from parse MultiMaterial data.
  31009. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31010. * @param scene - BJS scene.
  31011. * @returns - MultiMaterial.
  31012. */
  31013. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31014. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31015. multiMaterial.id = parsedMultiMaterial.id;
  31016. if (BABYLON.Tags) {
  31017. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31018. }
  31019. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31020. var subMatId = parsedMultiMaterial.materials[matIndex];
  31021. if (subMatId) {
  31022. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31023. }
  31024. else {
  31025. multiMaterial.subMaterials.push(null);
  31026. }
  31027. }
  31028. return multiMaterial;
  31029. };
  31030. /**
  31031. * Creates a material from parsed material data.
  31032. * @param parsedMaterial - Parsed material data.
  31033. * @param scene - BJS scene.
  31034. * @param rootUrl - Root URL containing the material information.
  31035. * @returns - Parsed material.
  31036. */
  31037. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31038. if (!parsedMaterial.customType) {
  31039. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31040. }
  31041. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31042. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31043. if (!BABYLON.LegacyPBRMaterial) {
  31044. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31045. return;
  31046. }
  31047. }
  31048. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31049. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31050. ;
  31051. };
  31052. // Triangle views
  31053. Material._TriangleFillMode = 0;
  31054. Material._WireFrameFillMode = 1;
  31055. Material._PointFillMode = 2;
  31056. // Draw modes
  31057. Material._PointListDrawMode = 3;
  31058. Material._LineListDrawMode = 4;
  31059. Material._LineLoopDrawMode = 5;
  31060. Material._LineStripDrawMode = 6;
  31061. Material._TriangleStripDrawMode = 7;
  31062. Material._TriangleFanDrawMode = 8;
  31063. /**
  31064. * Stores the clock-wise side orientation.
  31065. */
  31066. Material._ClockWiseSideOrientation = 0;
  31067. /**
  31068. * Stores the counter clock-wise side orientation.
  31069. */
  31070. Material._CounterClockWiseSideOrientation = 1;
  31071. /**
  31072. * The dirty texture flag value.
  31073. */
  31074. Material._TextureDirtyFlag = 1;
  31075. /**
  31076. * The dirty light flag value.
  31077. */
  31078. Material._LightDirtyFlag = 2;
  31079. /**
  31080. * The dirty fresnel flag value.
  31081. */
  31082. Material._FresnelDirtyFlag = 4;
  31083. /**
  31084. * The dirty attribute flag value.
  31085. */
  31086. Material._AttributesDirtyFlag = 8;
  31087. /**
  31088. * The dirty misc flag value.
  31089. */
  31090. Material._MiscDirtyFlag = 16;
  31091. __decorate([
  31092. BABYLON.serialize()
  31093. ], Material.prototype, "id", void 0);
  31094. __decorate([
  31095. BABYLON.serialize()
  31096. ], Material.prototype, "name", void 0);
  31097. __decorate([
  31098. BABYLON.serialize()
  31099. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31100. __decorate([
  31101. BABYLON.serialize()
  31102. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31103. __decorate([
  31104. BABYLON.serialize()
  31105. ], Material.prototype, "state", void 0);
  31106. __decorate([
  31107. BABYLON.serialize("alpha")
  31108. ], Material.prototype, "_alpha", void 0);
  31109. __decorate([
  31110. BABYLON.serialize("backFaceCulling")
  31111. ], Material.prototype, "_backFaceCulling", void 0);
  31112. __decorate([
  31113. BABYLON.serialize()
  31114. ], Material.prototype, "sideOrientation", void 0);
  31115. __decorate([
  31116. BABYLON.serialize("alphaMode")
  31117. ], Material.prototype, "_alphaMode", void 0);
  31118. __decorate([
  31119. BABYLON.serialize()
  31120. ], Material.prototype, "_needDepthPrePass", void 0);
  31121. __decorate([
  31122. BABYLON.serialize()
  31123. ], Material.prototype, "disableDepthWrite", void 0);
  31124. __decorate([
  31125. BABYLON.serialize()
  31126. ], Material.prototype, "forceDepthWrite", void 0);
  31127. __decorate([
  31128. BABYLON.serialize()
  31129. ], Material.prototype, "separateCullingPass", void 0);
  31130. __decorate([
  31131. BABYLON.serialize("fogEnabled")
  31132. ], Material.prototype, "_fogEnabled", void 0);
  31133. __decorate([
  31134. BABYLON.serialize()
  31135. ], Material.prototype, "pointSize", void 0);
  31136. __decorate([
  31137. BABYLON.serialize()
  31138. ], Material.prototype, "zOffset", void 0);
  31139. __decorate([
  31140. BABYLON.serialize()
  31141. ], Material.prototype, "wireframe", null);
  31142. __decorate([
  31143. BABYLON.serialize()
  31144. ], Material.prototype, "pointsCloud", null);
  31145. __decorate([
  31146. BABYLON.serialize()
  31147. ], Material.prototype, "fillMode", null);
  31148. return Material;
  31149. }());
  31150. BABYLON.Material = Material;
  31151. })(BABYLON || (BABYLON = {}));
  31152. //# sourceMappingURL=babylon.material.js.map
  31153. var BABYLON;
  31154. (function (BABYLON) {
  31155. var UniformBuffer = /** @class */ (function () {
  31156. /**
  31157. * Uniform buffer objects.
  31158. *
  31159. * Handles blocks of uniform on the GPU.
  31160. *
  31161. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31162. *
  31163. * For more information, please refer to :
  31164. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31165. */
  31166. function UniformBuffer(engine, data, dynamic) {
  31167. this._engine = engine;
  31168. this._noUBO = !engine.supportsUniformBuffers;
  31169. this._dynamic = dynamic;
  31170. this._data = data || [];
  31171. this._uniformLocations = {};
  31172. this._uniformSizes = {};
  31173. this._uniformLocationPointer = 0;
  31174. this._needSync = false;
  31175. if (this._noUBO) {
  31176. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31177. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31178. this.updateFloat = this._updateFloatForEffect;
  31179. this.updateFloat2 = this._updateFloat2ForEffect;
  31180. this.updateFloat3 = this._updateFloat3ForEffect;
  31181. this.updateFloat4 = this._updateFloat4ForEffect;
  31182. this.updateMatrix = this._updateMatrixForEffect;
  31183. this.updateVector3 = this._updateVector3ForEffect;
  31184. this.updateVector4 = this._updateVector4ForEffect;
  31185. this.updateColor3 = this._updateColor3ForEffect;
  31186. this.updateColor4 = this._updateColor4ForEffect;
  31187. }
  31188. else {
  31189. this._engine._uniformBuffers.push(this);
  31190. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31191. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31192. this.updateFloat = this._updateFloatForUniform;
  31193. this.updateFloat2 = this._updateFloat2ForUniform;
  31194. this.updateFloat3 = this._updateFloat3ForUniform;
  31195. this.updateFloat4 = this._updateFloat4ForUniform;
  31196. this.updateMatrix = this._updateMatrixForUniform;
  31197. this.updateVector3 = this._updateVector3ForUniform;
  31198. this.updateVector4 = this._updateVector4ForUniform;
  31199. this.updateColor3 = this._updateColor3ForUniform;
  31200. this.updateColor4 = this._updateColor4ForUniform;
  31201. }
  31202. }
  31203. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31204. // Properties
  31205. /**
  31206. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31207. * or just falling back on setUniformXXX calls.
  31208. */
  31209. get: function () {
  31210. return !this._noUBO;
  31211. },
  31212. enumerable: true,
  31213. configurable: true
  31214. });
  31215. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31216. /**
  31217. * Indicates if the WebGL underlying uniform buffer is in sync
  31218. * with the javascript cache data.
  31219. */
  31220. get: function () {
  31221. return !this._needSync;
  31222. },
  31223. enumerable: true,
  31224. configurable: true
  31225. });
  31226. /**
  31227. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31228. * Also, a dynamic UniformBuffer will disable cache verification and always
  31229. * update the underlying WebGL uniform buffer to the GPU.
  31230. */
  31231. UniformBuffer.prototype.isDynamic = function () {
  31232. return this._dynamic !== undefined;
  31233. };
  31234. /**
  31235. * The data cache on JS side.
  31236. */
  31237. UniformBuffer.prototype.getData = function () {
  31238. return this._bufferData;
  31239. };
  31240. /**
  31241. * The underlying WebGL Uniform buffer.
  31242. */
  31243. UniformBuffer.prototype.getBuffer = function () {
  31244. return this._buffer;
  31245. };
  31246. /**
  31247. * std140 layout specifies how to align data within an UBO structure.
  31248. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31249. * for specs.
  31250. */
  31251. UniformBuffer.prototype._fillAlignment = function (size) {
  31252. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31253. // and 4x4 matrices
  31254. // TODO : change if other types are used
  31255. var alignment;
  31256. if (size <= 2) {
  31257. alignment = size;
  31258. }
  31259. else {
  31260. alignment = 4;
  31261. }
  31262. if ((this._uniformLocationPointer % alignment) !== 0) {
  31263. var oldPointer = this._uniformLocationPointer;
  31264. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31265. var diff = this._uniformLocationPointer - oldPointer;
  31266. for (var i = 0; i < diff; i++) {
  31267. this._data.push(0);
  31268. }
  31269. }
  31270. };
  31271. /**
  31272. * Adds an uniform in the buffer.
  31273. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31274. * for the layout to be correct !
  31275. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31276. * @param {number|number[]} size Data size, or data directly.
  31277. */
  31278. UniformBuffer.prototype.addUniform = function (name, size) {
  31279. if (this._noUBO) {
  31280. return;
  31281. }
  31282. if (this._uniformLocations[name] !== undefined) {
  31283. // Already existing uniform
  31284. return;
  31285. }
  31286. // This function must be called in the order of the shader layout !
  31287. // size can be the size of the uniform, or data directly
  31288. var data;
  31289. if (size instanceof Array) {
  31290. data = size;
  31291. size = data.length;
  31292. }
  31293. else {
  31294. size = size;
  31295. data = [];
  31296. // Fill with zeros
  31297. for (var i = 0; i < size; i++) {
  31298. data.push(0);
  31299. }
  31300. }
  31301. this._fillAlignment(size);
  31302. this._uniformSizes[name] = size;
  31303. this._uniformLocations[name] = this._uniformLocationPointer;
  31304. this._uniformLocationPointer += size;
  31305. for (var i = 0; i < size; i++) {
  31306. this._data.push(data[i]);
  31307. }
  31308. this._needSync = true;
  31309. };
  31310. /**
  31311. * Wrapper for addUniform.
  31312. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31313. * @param {Matrix} mat A 4x4 matrix.
  31314. */
  31315. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31316. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31317. };
  31318. /**
  31319. * Wrapper for addUniform.
  31320. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31321. * @param {number} x
  31322. * @param {number} y
  31323. */
  31324. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31325. var temp = [x, y];
  31326. this.addUniform(name, temp);
  31327. };
  31328. /**
  31329. * Wrapper for addUniform.
  31330. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31331. * @param {number} x
  31332. * @param {number} y
  31333. * @param {number} z
  31334. */
  31335. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31336. var temp = [x, y, z];
  31337. this.addUniform(name, temp);
  31338. };
  31339. /**
  31340. * Wrapper for addUniform.
  31341. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31342. * @param {Color3} color
  31343. */
  31344. UniformBuffer.prototype.addColor3 = function (name, color) {
  31345. var temp = new Array();
  31346. color.toArray(temp);
  31347. this.addUniform(name, temp);
  31348. };
  31349. /**
  31350. * Wrapper for addUniform.
  31351. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31352. * @param {Color3} color
  31353. * @param {number} alpha
  31354. */
  31355. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31356. var temp = new Array();
  31357. color.toArray(temp);
  31358. temp.push(alpha);
  31359. this.addUniform(name, temp);
  31360. };
  31361. /**
  31362. * Wrapper for addUniform.
  31363. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31364. * @param {Vector3} vector
  31365. */
  31366. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31367. var temp = new Array();
  31368. vector.toArray(temp);
  31369. this.addUniform(name, temp);
  31370. };
  31371. /**
  31372. * Wrapper for addUniform.
  31373. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31374. */
  31375. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31376. this.addUniform(name, 12);
  31377. };
  31378. /**
  31379. * Wrapper for addUniform.
  31380. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31381. */
  31382. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31383. this.addUniform(name, 8);
  31384. };
  31385. /**
  31386. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31387. */
  31388. UniformBuffer.prototype.create = function () {
  31389. if (this._noUBO) {
  31390. return;
  31391. }
  31392. if (this._buffer) {
  31393. return; // nothing to do
  31394. }
  31395. // See spec, alignment must be filled as a vec4
  31396. this._fillAlignment(4);
  31397. this._bufferData = new Float32Array(this._data);
  31398. this._rebuild();
  31399. this._needSync = true;
  31400. };
  31401. UniformBuffer.prototype._rebuild = function () {
  31402. if (this._noUBO) {
  31403. return;
  31404. }
  31405. if (this._dynamic) {
  31406. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31407. }
  31408. else {
  31409. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31410. }
  31411. };
  31412. /**
  31413. * Updates the WebGL Uniform Buffer on the GPU.
  31414. * If the `dynamic` flag is set to true, no cache comparison is done.
  31415. * Otherwise, the buffer will be updated only if the cache differs.
  31416. */
  31417. UniformBuffer.prototype.update = function () {
  31418. if (!this._buffer) {
  31419. this.create();
  31420. return;
  31421. }
  31422. if (!this._dynamic && !this._needSync) {
  31423. return;
  31424. }
  31425. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31426. this._needSync = false;
  31427. };
  31428. /**
  31429. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31430. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31431. * @param {number[]|Float32Array} data Flattened data
  31432. * @param {number} size Size of the data.
  31433. */
  31434. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31435. var location = this._uniformLocations[uniformName];
  31436. if (location === undefined) {
  31437. if (this._buffer) {
  31438. // Cannot add an uniform if the buffer is already created
  31439. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31440. return;
  31441. }
  31442. this.addUniform(uniformName, size);
  31443. location = this._uniformLocations[uniformName];
  31444. }
  31445. if (!this._buffer) {
  31446. this.create();
  31447. }
  31448. if (!this._dynamic) {
  31449. // Cache for static uniform buffers
  31450. var changed = false;
  31451. for (var i = 0; i < size; i++) {
  31452. if (this._bufferData[location + i] !== data[i]) {
  31453. changed = true;
  31454. this._bufferData[location + i] = data[i];
  31455. }
  31456. }
  31457. this._needSync = this._needSync || changed;
  31458. }
  31459. else {
  31460. // No cache for dynamic
  31461. for (var i = 0; i < size; i++) {
  31462. this._bufferData[location + i] = data[i];
  31463. }
  31464. }
  31465. };
  31466. // Update methods
  31467. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31468. // To match std140, matrix must be realigned
  31469. for (var i = 0; i < 3; i++) {
  31470. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31471. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31472. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31473. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31474. }
  31475. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31476. };
  31477. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31478. this._currentEffect.setMatrix3x3(name, matrix);
  31479. };
  31480. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31481. this._currentEffect.setMatrix2x2(name, matrix);
  31482. };
  31483. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31484. // To match std140, matrix must be realigned
  31485. for (var i = 0; i < 2; i++) {
  31486. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31487. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31488. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31489. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31490. }
  31491. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31492. };
  31493. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31494. this._currentEffect.setFloat(name, x);
  31495. };
  31496. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31497. UniformBuffer._tempBuffer[0] = x;
  31498. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31499. };
  31500. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31501. if (suffix === void 0) { suffix = ""; }
  31502. this._currentEffect.setFloat2(name + suffix, x, y);
  31503. };
  31504. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31505. if (suffix === void 0) { suffix = ""; }
  31506. UniformBuffer._tempBuffer[0] = x;
  31507. UniformBuffer._tempBuffer[1] = y;
  31508. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31509. };
  31510. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31511. if (suffix === void 0) { suffix = ""; }
  31512. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31513. };
  31514. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31515. if (suffix === void 0) { suffix = ""; }
  31516. UniformBuffer._tempBuffer[0] = x;
  31517. UniformBuffer._tempBuffer[1] = y;
  31518. UniformBuffer._tempBuffer[2] = z;
  31519. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31520. };
  31521. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31522. if (suffix === void 0) { suffix = ""; }
  31523. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31524. };
  31525. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31526. if (suffix === void 0) { suffix = ""; }
  31527. UniformBuffer._tempBuffer[0] = x;
  31528. UniformBuffer._tempBuffer[1] = y;
  31529. UniformBuffer._tempBuffer[2] = z;
  31530. UniformBuffer._tempBuffer[3] = w;
  31531. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31532. };
  31533. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31534. this._currentEffect.setMatrix(name, mat);
  31535. };
  31536. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31537. this.updateUniform(name, mat.toArray(), 16);
  31538. };
  31539. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31540. this._currentEffect.setVector3(name, vector);
  31541. };
  31542. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31543. vector.toArray(UniformBuffer._tempBuffer);
  31544. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31545. };
  31546. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31547. this._currentEffect.setVector4(name, vector);
  31548. };
  31549. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31550. vector.toArray(UniformBuffer._tempBuffer);
  31551. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31552. };
  31553. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31554. if (suffix === void 0) { suffix = ""; }
  31555. this._currentEffect.setColor3(name + suffix, color);
  31556. };
  31557. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31558. if (suffix === void 0) { suffix = ""; }
  31559. color.toArray(UniformBuffer._tempBuffer);
  31560. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31561. };
  31562. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31563. if (suffix === void 0) { suffix = ""; }
  31564. this._currentEffect.setColor4(name + suffix, color, alpha);
  31565. };
  31566. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31567. if (suffix === void 0) { suffix = ""; }
  31568. color.toArray(UniformBuffer._tempBuffer);
  31569. UniformBuffer._tempBuffer[3] = alpha;
  31570. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31571. };
  31572. /**
  31573. * Sets a sampler uniform on the effect.
  31574. * @param {string} name Name of the sampler.
  31575. * @param {Texture} texture
  31576. */
  31577. UniformBuffer.prototype.setTexture = function (name, texture) {
  31578. this._currentEffect.setTexture(name, texture);
  31579. };
  31580. /**
  31581. * Directly updates the value of the uniform in the cache AND on the GPU.
  31582. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31583. * @param {number[]|Float32Array} data Flattened data
  31584. */
  31585. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31586. this.updateUniform(uniformName, data, data.length);
  31587. this.update();
  31588. };
  31589. /**
  31590. * Binds this uniform buffer to an effect.
  31591. * @param {Effect} effect
  31592. * @param {string} name Name of the uniform block in the shader.
  31593. */
  31594. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31595. this._currentEffect = effect;
  31596. if (this._noUBO || !this._buffer) {
  31597. return;
  31598. }
  31599. effect.bindUniformBuffer(this._buffer, name);
  31600. };
  31601. /**
  31602. * Disposes the uniform buffer.
  31603. */
  31604. UniformBuffer.prototype.dispose = function () {
  31605. if (this._noUBO) {
  31606. return;
  31607. }
  31608. var index = this._engine._uniformBuffers.indexOf(this);
  31609. if (index !== -1) {
  31610. this._engine._uniformBuffers.splice(index, 1);
  31611. }
  31612. if (!this._buffer) {
  31613. return;
  31614. }
  31615. if (this._engine._releaseBuffer(this._buffer)) {
  31616. this._buffer = null;
  31617. }
  31618. };
  31619. // Pool for avoiding memory leaks
  31620. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31621. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31622. return UniformBuffer;
  31623. }());
  31624. BABYLON.UniformBuffer = UniformBuffer;
  31625. })(BABYLON || (BABYLON = {}));
  31626. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31627. var BABYLON;
  31628. (function (BABYLON) {
  31629. var VertexData = /** @class */ (function () {
  31630. function VertexData() {
  31631. }
  31632. VertexData.prototype.set = function (data, kind) {
  31633. switch (kind) {
  31634. case BABYLON.VertexBuffer.PositionKind:
  31635. this.positions = data;
  31636. break;
  31637. case BABYLON.VertexBuffer.NormalKind:
  31638. this.normals = data;
  31639. break;
  31640. case BABYLON.VertexBuffer.TangentKind:
  31641. this.tangents = data;
  31642. break;
  31643. case BABYLON.VertexBuffer.UVKind:
  31644. this.uvs = data;
  31645. break;
  31646. case BABYLON.VertexBuffer.UV2Kind:
  31647. this.uvs2 = data;
  31648. break;
  31649. case BABYLON.VertexBuffer.UV3Kind:
  31650. this.uvs3 = data;
  31651. break;
  31652. case BABYLON.VertexBuffer.UV4Kind:
  31653. this.uvs4 = data;
  31654. break;
  31655. case BABYLON.VertexBuffer.UV5Kind:
  31656. this.uvs5 = data;
  31657. break;
  31658. case BABYLON.VertexBuffer.UV6Kind:
  31659. this.uvs6 = data;
  31660. break;
  31661. case BABYLON.VertexBuffer.ColorKind:
  31662. this.colors = data;
  31663. break;
  31664. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31665. this.matricesIndices = data;
  31666. break;
  31667. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31668. this.matricesWeights = data;
  31669. break;
  31670. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31671. this.matricesIndicesExtra = data;
  31672. break;
  31673. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31674. this.matricesWeightsExtra = data;
  31675. break;
  31676. }
  31677. };
  31678. /**
  31679. * Associates the vertexData to the passed Mesh.
  31680. * Sets it as updatable or not (default `false`).
  31681. * Returns the VertexData.
  31682. */
  31683. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31684. this._applyTo(mesh, updatable);
  31685. return this;
  31686. };
  31687. /**
  31688. * Associates the vertexData to the passed Geometry.
  31689. * Sets it as updatable or not (default `false`).
  31690. * Returns the VertexData.
  31691. */
  31692. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31693. this._applyTo(geometry, updatable);
  31694. return this;
  31695. };
  31696. /**
  31697. * Updates the associated mesh.
  31698. * Returns the VertexData.
  31699. */
  31700. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31701. this._update(mesh);
  31702. return this;
  31703. };
  31704. /**
  31705. * Updates the associated geometry.
  31706. * Returns the VertexData.
  31707. */
  31708. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31709. this._update(geometry);
  31710. return this;
  31711. };
  31712. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31713. if (updatable === void 0) { updatable = false; }
  31714. if (this.positions) {
  31715. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31716. }
  31717. if (this.normals) {
  31718. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31719. }
  31720. if (this.tangents) {
  31721. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  31722. }
  31723. if (this.uvs) {
  31724. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31725. }
  31726. if (this.uvs2) {
  31727. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31728. }
  31729. if (this.uvs3) {
  31730. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31731. }
  31732. if (this.uvs4) {
  31733. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  31734. }
  31735. if (this.uvs5) {
  31736. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  31737. }
  31738. if (this.uvs6) {
  31739. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  31740. }
  31741. if (this.colors) {
  31742. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  31743. }
  31744. if (this.matricesIndices) {
  31745. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  31746. }
  31747. if (this.matricesWeights) {
  31748. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  31749. }
  31750. if (this.matricesIndicesExtra) {
  31751. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  31752. }
  31753. if (this.matricesWeightsExtra) {
  31754. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  31755. }
  31756. if (this.indices) {
  31757. meshOrGeometry.setIndices(this.indices, null, updatable);
  31758. }
  31759. return this;
  31760. };
  31761. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  31762. if (this.positions) {
  31763. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  31764. }
  31765. if (this.normals) {
  31766. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  31767. }
  31768. if (this.tangents) {
  31769. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  31770. }
  31771. if (this.uvs) {
  31772. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  31773. }
  31774. if (this.uvs2) {
  31775. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  31776. }
  31777. if (this.uvs3) {
  31778. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  31779. }
  31780. if (this.uvs4) {
  31781. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  31782. }
  31783. if (this.uvs5) {
  31784. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  31785. }
  31786. if (this.uvs6) {
  31787. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  31788. }
  31789. if (this.colors) {
  31790. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  31791. }
  31792. if (this.matricesIndices) {
  31793. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  31794. }
  31795. if (this.matricesWeights) {
  31796. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  31797. }
  31798. if (this.matricesIndicesExtra) {
  31799. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  31800. }
  31801. if (this.matricesWeightsExtra) {
  31802. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  31803. }
  31804. if (this.indices) {
  31805. meshOrGeometry.setIndices(this.indices, null);
  31806. }
  31807. return this;
  31808. };
  31809. /**
  31810. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  31811. * Returns the VertexData.
  31812. */
  31813. VertexData.prototype.transform = function (matrix) {
  31814. var transformed = BABYLON.Vector3.Zero();
  31815. var index;
  31816. if (this.positions) {
  31817. var position = BABYLON.Vector3.Zero();
  31818. for (index = 0; index < this.positions.length; index += 3) {
  31819. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  31820. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  31821. this.positions[index] = transformed.x;
  31822. this.positions[index + 1] = transformed.y;
  31823. this.positions[index + 2] = transformed.z;
  31824. }
  31825. }
  31826. if (this.normals) {
  31827. var normal = BABYLON.Vector3.Zero();
  31828. for (index = 0; index < this.normals.length; index += 3) {
  31829. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  31830. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  31831. this.normals[index] = transformed.x;
  31832. this.normals[index + 1] = transformed.y;
  31833. this.normals[index + 2] = transformed.z;
  31834. }
  31835. }
  31836. if (this.tangents) {
  31837. var tangent = BABYLON.Vector4.Zero();
  31838. var tangentTransformed = BABYLON.Vector4.Zero();
  31839. for (index = 0; index < this.tangents.length; index += 4) {
  31840. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  31841. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  31842. this.tangents[index] = tangentTransformed.x;
  31843. this.tangents[index + 1] = tangentTransformed.y;
  31844. this.tangents[index + 2] = tangentTransformed.z;
  31845. this.tangents[index + 3] = tangentTransformed.w;
  31846. }
  31847. }
  31848. return this;
  31849. };
  31850. /**
  31851. * Merges the passed VertexData into the current one.
  31852. * Returns the modified VertexData.
  31853. */
  31854. VertexData.prototype.merge = function (other) {
  31855. this._validate();
  31856. other._validate();
  31857. if (!this.normals !== !other.normals ||
  31858. !this.tangents !== !other.tangents ||
  31859. !this.uvs !== !other.uvs ||
  31860. !this.uvs2 !== !other.uvs2 ||
  31861. !this.uvs3 !== !other.uvs3 ||
  31862. !this.uvs4 !== !other.uvs4 ||
  31863. !this.uvs5 !== !other.uvs5 ||
  31864. !this.uvs6 !== !other.uvs6 ||
  31865. !this.colors !== !other.colors ||
  31866. !this.matricesIndices !== !other.matricesIndices ||
  31867. !this.matricesWeights !== !other.matricesWeights ||
  31868. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  31869. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  31870. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  31871. }
  31872. if (other.indices) {
  31873. if (!this.indices) {
  31874. this.indices = [];
  31875. }
  31876. var offset = this.positions ? this.positions.length / 3 : 0;
  31877. for (var index = 0; index < other.indices.length; index++) {
  31878. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  31879. this.indices.push(other.indices[index] + offset);
  31880. }
  31881. }
  31882. this.positions = this._mergeElement(this.positions, other.positions);
  31883. this.normals = this._mergeElement(this.normals, other.normals);
  31884. this.tangents = this._mergeElement(this.tangents, other.tangents);
  31885. this.uvs = this._mergeElement(this.uvs, other.uvs);
  31886. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  31887. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  31888. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  31889. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  31890. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  31891. this.colors = this._mergeElement(this.colors, other.colors);
  31892. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  31893. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  31894. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  31895. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  31896. return this;
  31897. };
  31898. VertexData.prototype._mergeElement = function (source, other) {
  31899. if (!source) {
  31900. return other;
  31901. }
  31902. if (!other) {
  31903. return source;
  31904. }
  31905. var len = other.length + source.length;
  31906. var isSrcTypedArray = source instanceof Float32Array;
  31907. var isOthTypedArray = other instanceof Float32Array;
  31908. // use non-loop method when the source is Float32Array
  31909. if (isSrcTypedArray) {
  31910. var ret32 = new Float32Array(len);
  31911. ret32.set(source);
  31912. ret32.set(other, source.length);
  31913. return ret32;
  31914. // source is number[], when other is also use concat
  31915. }
  31916. else if (!isOthTypedArray) {
  31917. return source.concat(other);
  31918. // source is a number[], but other is a Float32Array, loop required
  31919. }
  31920. else {
  31921. var ret = source.slice(0); // copy source to a separate array
  31922. for (var i = 0, len = other.length; i < len; i++) {
  31923. ret.push(other[i]);
  31924. }
  31925. return ret;
  31926. }
  31927. };
  31928. VertexData.prototype._validate = function () {
  31929. if (!this.positions) {
  31930. throw new Error("Positions are required");
  31931. }
  31932. var getElementCount = function (kind, values) {
  31933. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  31934. if ((values.length % stride) !== 0) {
  31935. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  31936. }
  31937. return values.length / stride;
  31938. };
  31939. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  31940. var validateElementCount = function (kind, values) {
  31941. var elementCount = getElementCount(kind, values);
  31942. if (elementCount !== positionsElementCount) {
  31943. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  31944. }
  31945. };
  31946. if (this.normals)
  31947. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  31948. if (this.tangents)
  31949. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  31950. if (this.uvs)
  31951. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  31952. if (this.uvs2)
  31953. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  31954. if (this.uvs3)
  31955. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  31956. if (this.uvs4)
  31957. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  31958. if (this.uvs5)
  31959. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  31960. if (this.uvs6)
  31961. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  31962. if (this.colors)
  31963. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  31964. if (this.matricesIndices)
  31965. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  31966. if (this.matricesWeights)
  31967. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  31968. if (this.matricesIndicesExtra)
  31969. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  31970. if (this.matricesWeightsExtra)
  31971. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  31972. };
  31973. /**
  31974. * Serializes the VertexData.
  31975. * Returns a serialized object.
  31976. */
  31977. VertexData.prototype.serialize = function () {
  31978. var serializationObject = this.serialize();
  31979. if (this.positions) {
  31980. serializationObject.positions = this.positions;
  31981. }
  31982. if (this.normals) {
  31983. serializationObject.normals = this.normals;
  31984. }
  31985. if (this.tangents) {
  31986. serializationObject.tangents = this.tangents;
  31987. }
  31988. if (this.uvs) {
  31989. serializationObject.uvs = this.uvs;
  31990. }
  31991. if (this.uvs2) {
  31992. serializationObject.uvs2 = this.uvs2;
  31993. }
  31994. if (this.uvs3) {
  31995. serializationObject.uvs3 = this.uvs3;
  31996. }
  31997. if (this.uvs4) {
  31998. serializationObject.uvs4 = this.uvs4;
  31999. }
  32000. if (this.uvs5) {
  32001. serializationObject.uvs5 = this.uvs5;
  32002. }
  32003. if (this.uvs6) {
  32004. serializationObject.uvs6 = this.uvs6;
  32005. }
  32006. if (this.colors) {
  32007. serializationObject.colors = this.colors;
  32008. }
  32009. if (this.matricesIndices) {
  32010. serializationObject.matricesIndices = this.matricesIndices;
  32011. serializationObject.matricesIndices._isExpanded = true;
  32012. }
  32013. if (this.matricesWeights) {
  32014. serializationObject.matricesWeights = this.matricesWeights;
  32015. }
  32016. if (this.matricesIndicesExtra) {
  32017. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32018. serializationObject.matricesIndicesExtra._isExpanded = true;
  32019. }
  32020. if (this.matricesWeightsExtra) {
  32021. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32022. }
  32023. serializationObject.indices = this.indices;
  32024. return serializationObject;
  32025. };
  32026. // Statics
  32027. /**
  32028. * Returns the object VertexData associated to the passed mesh.
  32029. */
  32030. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32031. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32032. };
  32033. /**
  32034. * Returns the object VertexData associated to the passed geometry.
  32035. */
  32036. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32037. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32038. };
  32039. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32040. var result = new VertexData();
  32041. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32042. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32043. }
  32044. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32045. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32046. }
  32047. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32048. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32049. }
  32050. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32051. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32052. }
  32053. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32054. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32055. }
  32056. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32057. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32058. }
  32059. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32060. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32061. }
  32062. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32063. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32064. }
  32065. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32066. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32067. }
  32068. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32069. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32070. }
  32071. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32072. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32073. }
  32074. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32075. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32076. }
  32077. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32078. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32079. }
  32080. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32081. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32082. }
  32083. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32084. return result;
  32085. };
  32086. /**
  32087. * Creates the vertexData of the Ribbon.
  32088. */
  32089. VertexData.CreateRibbon = function (options) {
  32090. var pathArray = options.pathArray;
  32091. var closeArray = options.closeArray || false;
  32092. var closePath = options.closePath || false;
  32093. var invertUV = options.invertUV || false;
  32094. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32095. var offset = options.offset || defaultOffset;
  32096. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32097. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32098. var customUV = options.uvs;
  32099. var customColors = options.colors;
  32100. var positions = [];
  32101. var indices = [];
  32102. var normals = [];
  32103. var uvs = [];
  32104. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32105. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32106. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32107. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32108. var minlg; // minimal length among all paths from pathArray
  32109. var lg = []; // array of path lengths : nb of vertex per path
  32110. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32111. var p; // path iterator
  32112. var i; // point iterator
  32113. var j; // point iterator
  32114. // if single path in pathArray
  32115. if (pathArray.length < 2) {
  32116. var ar1 = [];
  32117. var ar2 = [];
  32118. for (i = 0; i < pathArray[0].length - offset; i++) {
  32119. ar1.push(pathArray[0][i]);
  32120. ar2.push(pathArray[0][i + offset]);
  32121. }
  32122. pathArray = [ar1, ar2];
  32123. }
  32124. // positions and horizontal distances (u)
  32125. var idc = 0;
  32126. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32127. var path;
  32128. var l;
  32129. minlg = pathArray[0].length;
  32130. var vectlg;
  32131. var dist;
  32132. for (p = 0; p < pathArray.length; p++) {
  32133. uTotalDistance[p] = 0;
  32134. us[p] = [0];
  32135. path = pathArray[p];
  32136. l = path.length;
  32137. minlg = (minlg < l) ? minlg : l;
  32138. j = 0;
  32139. while (j < l) {
  32140. positions.push(path[j].x, path[j].y, path[j].z);
  32141. if (j > 0) {
  32142. vectlg = path[j].subtract(path[j - 1]).length();
  32143. dist = vectlg + uTotalDistance[p];
  32144. us[p].push(dist);
  32145. uTotalDistance[p] = dist;
  32146. }
  32147. j++;
  32148. }
  32149. if (closePath) {
  32150. j--;
  32151. positions.push(path[0].x, path[0].y, path[0].z);
  32152. vectlg = path[j].subtract(path[0]).length();
  32153. dist = vectlg + uTotalDistance[p];
  32154. us[p].push(dist);
  32155. uTotalDistance[p] = dist;
  32156. }
  32157. lg[p] = l + closePathCorr;
  32158. idx[p] = idc;
  32159. idc += (l + closePathCorr);
  32160. }
  32161. // vertical distances (v)
  32162. var path1;
  32163. var path2;
  32164. var vertex1 = null;
  32165. var vertex2 = null;
  32166. for (i = 0; i < minlg + closePathCorr; i++) {
  32167. vTotalDistance[i] = 0;
  32168. vs[i] = [0];
  32169. for (p = 0; p < pathArray.length - 1; p++) {
  32170. path1 = pathArray[p];
  32171. path2 = pathArray[p + 1];
  32172. if (i === minlg) {
  32173. vertex1 = path1[0];
  32174. vertex2 = path2[0];
  32175. }
  32176. else {
  32177. vertex1 = path1[i];
  32178. vertex2 = path2[i];
  32179. }
  32180. vectlg = vertex2.subtract(vertex1).length();
  32181. dist = vectlg + vTotalDistance[i];
  32182. vs[i].push(dist);
  32183. vTotalDistance[i] = dist;
  32184. }
  32185. if (closeArray && vertex2 && vertex1) {
  32186. path1 = pathArray[p];
  32187. path2 = pathArray[0];
  32188. if (i === minlg) {
  32189. vertex2 = path2[0];
  32190. }
  32191. vectlg = vertex2.subtract(vertex1).length();
  32192. dist = vectlg + vTotalDistance[i];
  32193. vTotalDistance[i] = dist;
  32194. }
  32195. }
  32196. // uvs
  32197. var u;
  32198. var v;
  32199. if (customUV) {
  32200. for (p = 0; p < customUV.length; p++) {
  32201. uvs.push(customUV[p].x, customUV[p].y);
  32202. }
  32203. }
  32204. else {
  32205. for (p = 0; p < pathArray.length; p++) {
  32206. for (i = 0; i < minlg + closePathCorr; i++) {
  32207. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32208. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32209. if (invertUV) {
  32210. uvs.push(v, u);
  32211. }
  32212. else {
  32213. uvs.push(u, v);
  32214. }
  32215. }
  32216. }
  32217. }
  32218. // indices
  32219. p = 0; // path index
  32220. var pi = 0; // positions array index
  32221. var l1 = lg[p] - 1; // path1 length
  32222. var l2 = lg[p + 1] - 1; // path2 length
  32223. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32224. var shft = idx[1] - idx[0]; // shift
  32225. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32226. while (pi <= min && p < path1nb) {
  32227. // 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
  32228. indices.push(pi, pi + shft, pi + 1);
  32229. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32230. pi += 1;
  32231. if (pi === min) {
  32232. p++;
  32233. if (p === lg.length - 1) {
  32234. shft = idx[0] - idx[p];
  32235. l1 = lg[p] - 1;
  32236. l2 = lg[0] - 1;
  32237. }
  32238. else {
  32239. shft = idx[p + 1] - idx[p];
  32240. l1 = lg[p] - 1;
  32241. l2 = lg[p + 1] - 1;
  32242. }
  32243. pi = idx[p];
  32244. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32245. }
  32246. }
  32247. // normals
  32248. VertexData.ComputeNormals(positions, indices, normals);
  32249. if (closePath) {
  32250. var indexFirst = 0;
  32251. var indexLast = 0;
  32252. for (p = 0; p < pathArray.length; p++) {
  32253. indexFirst = idx[p] * 3;
  32254. if (p + 1 < pathArray.length) {
  32255. indexLast = (idx[p + 1] - 1) * 3;
  32256. }
  32257. else {
  32258. indexLast = normals.length - 3;
  32259. }
  32260. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32261. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32262. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32263. normals[indexLast] = normals[indexFirst];
  32264. normals[indexLast + 1] = normals[indexFirst + 1];
  32265. normals[indexLast + 2] = normals[indexFirst + 2];
  32266. }
  32267. }
  32268. // sides
  32269. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32270. // Colors
  32271. var colors = null;
  32272. if (customColors) {
  32273. colors = new Float32Array(customColors.length * 4);
  32274. for (var c = 0; c < customColors.length; c++) {
  32275. colors[c * 4] = customColors[c].r;
  32276. colors[c * 4 + 1] = customColors[c].g;
  32277. colors[c * 4 + 2] = customColors[c].b;
  32278. colors[c * 4 + 3] = customColors[c].a;
  32279. }
  32280. }
  32281. // Result
  32282. var vertexData = new VertexData();
  32283. var positions32 = new Float32Array(positions);
  32284. var normals32 = new Float32Array(normals);
  32285. var uvs32 = new Float32Array(uvs);
  32286. vertexData.indices = indices;
  32287. vertexData.positions = positions32;
  32288. vertexData.normals = normals32;
  32289. vertexData.uvs = uvs32;
  32290. if (colors) {
  32291. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32292. }
  32293. if (closePath) {
  32294. vertexData._idx = idx;
  32295. }
  32296. return vertexData;
  32297. };
  32298. /**
  32299. * Creates the VertexData of the Box.
  32300. */
  32301. VertexData.CreateBox = function (options) {
  32302. var normalsSource = [
  32303. new BABYLON.Vector3(0, 0, 1),
  32304. new BABYLON.Vector3(0, 0, -1),
  32305. new BABYLON.Vector3(1, 0, 0),
  32306. new BABYLON.Vector3(-1, 0, 0),
  32307. new BABYLON.Vector3(0, 1, 0),
  32308. new BABYLON.Vector3(0, -1, 0)
  32309. ];
  32310. var indices = [];
  32311. var positions = [];
  32312. var normals = [];
  32313. var uvs = [];
  32314. var width = options.width || options.size || 1;
  32315. var height = options.height || options.size || 1;
  32316. var depth = options.depth || options.size || 1;
  32317. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32318. var faceUV = options.faceUV || new Array(6);
  32319. var faceColors = options.faceColors;
  32320. var colors = [];
  32321. // default face colors and UV if undefined
  32322. for (var f = 0; f < 6; f++) {
  32323. if (faceUV[f] === undefined) {
  32324. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32325. }
  32326. if (faceColors && faceColors[f] === undefined) {
  32327. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32328. }
  32329. }
  32330. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32331. // Create each face in turn.
  32332. for (var index = 0; index < normalsSource.length; index++) {
  32333. var normal = normalsSource[index];
  32334. // Get two vectors perpendicular to the face normal and to each other.
  32335. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32336. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32337. // Six indices (two triangles) per face.
  32338. var verticesLength = positions.length / 3;
  32339. indices.push(verticesLength);
  32340. indices.push(verticesLength + 1);
  32341. indices.push(verticesLength + 2);
  32342. indices.push(verticesLength);
  32343. indices.push(verticesLength + 2);
  32344. indices.push(verticesLength + 3);
  32345. // Four vertices per face.
  32346. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32347. positions.push(vertex.x, vertex.y, vertex.z);
  32348. normals.push(normal.x, normal.y, normal.z);
  32349. uvs.push(faceUV[index].z, faceUV[index].w);
  32350. if (faceColors) {
  32351. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32352. }
  32353. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32354. positions.push(vertex.x, vertex.y, vertex.z);
  32355. normals.push(normal.x, normal.y, normal.z);
  32356. uvs.push(faceUV[index].x, faceUV[index].w);
  32357. if (faceColors) {
  32358. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32359. }
  32360. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32361. positions.push(vertex.x, vertex.y, vertex.z);
  32362. normals.push(normal.x, normal.y, normal.z);
  32363. uvs.push(faceUV[index].x, faceUV[index].y);
  32364. if (faceColors) {
  32365. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32366. }
  32367. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32368. positions.push(vertex.x, vertex.y, vertex.z);
  32369. normals.push(normal.x, normal.y, normal.z);
  32370. uvs.push(faceUV[index].z, faceUV[index].y);
  32371. if (faceColors) {
  32372. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32373. }
  32374. }
  32375. // sides
  32376. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32377. // Result
  32378. var vertexData = new VertexData();
  32379. vertexData.indices = indices;
  32380. vertexData.positions = positions;
  32381. vertexData.normals = normals;
  32382. vertexData.uvs = uvs;
  32383. if (faceColors) {
  32384. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32385. vertexData.colors = totalColors;
  32386. }
  32387. return vertexData;
  32388. };
  32389. /**
  32390. * Creates the VertexData of the Sphere.
  32391. */
  32392. VertexData.CreateSphere = function (options) {
  32393. var segments = options.segments || 32;
  32394. var diameterX = options.diameterX || options.diameter || 1;
  32395. var diameterY = options.diameterY || options.diameter || 1;
  32396. var diameterZ = options.diameterZ || options.diameter || 1;
  32397. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32398. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32399. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32400. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32401. var totalZRotationSteps = 2 + segments;
  32402. var totalYRotationSteps = 2 * totalZRotationSteps;
  32403. var indices = [];
  32404. var positions = [];
  32405. var normals = [];
  32406. var uvs = [];
  32407. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32408. var normalizedZ = zRotationStep / totalZRotationSteps;
  32409. var angleZ = normalizedZ * Math.PI * slice;
  32410. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32411. var normalizedY = yRotationStep / totalYRotationSteps;
  32412. var angleY = normalizedY * Math.PI * 2 * arc;
  32413. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32414. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32415. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32416. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32417. var vertex = complete.multiply(radius);
  32418. var normal = complete.divide(radius).normalize();
  32419. positions.push(vertex.x, vertex.y, vertex.z);
  32420. normals.push(normal.x, normal.y, normal.z);
  32421. uvs.push(normalizedY, normalizedZ);
  32422. }
  32423. if (zRotationStep > 0) {
  32424. var verticesCount = positions.length / 3;
  32425. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32426. indices.push((firstIndex));
  32427. indices.push((firstIndex + 1));
  32428. indices.push(firstIndex + totalYRotationSteps + 1);
  32429. indices.push((firstIndex + totalYRotationSteps + 1));
  32430. indices.push((firstIndex + 1));
  32431. indices.push((firstIndex + totalYRotationSteps + 2));
  32432. }
  32433. }
  32434. }
  32435. // Sides
  32436. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32437. // Result
  32438. var vertexData = new VertexData();
  32439. vertexData.indices = indices;
  32440. vertexData.positions = positions;
  32441. vertexData.normals = normals;
  32442. vertexData.uvs = uvs;
  32443. return vertexData;
  32444. };
  32445. /**
  32446. * Creates the VertexData of the Cylinder or Cone.
  32447. */
  32448. VertexData.CreateCylinder = function (options) {
  32449. var height = options.height || 2;
  32450. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32451. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32452. var tessellation = options.tessellation || 24;
  32453. var subdivisions = options.subdivisions || 1;
  32454. var hasRings = options.hasRings ? true : false;
  32455. var enclose = options.enclose ? true : false;
  32456. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32457. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32458. var faceUV = options.faceUV || new Array(3);
  32459. var faceColors = options.faceColors;
  32460. // default face colors and UV if undefined
  32461. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32462. var ringNb = (hasRings) ? subdivisions : 1;
  32463. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32464. var f;
  32465. for (f = 0; f < surfaceNb; f++) {
  32466. if (faceColors && faceColors[f] === undefined) {
  32467. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32468. }
  32469. }
  32470. for (f = 0; f < surfaceNb; f++) {
  32471. if (faceUV && faceUV[f] === undefined) {
  32472. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32473. }
  32474. }
  32475. var indices = new Array();
  32476. var positions = new Array();
  32477. var normals = new Array();
  32478. var uvs = new Array();
  32479. var colors = new Array();
  32480. var angle_step = Math.PI * 2 * arc / tessellation;
  32481. var angle;
  32482. var h;
  32483. var radius;
  32484. var tan = (diameterBottom - diameterTop) / 2 / height;
  32485. var ringVertex = BABYLON.Vector3.Zero();
  32486. var ringNormal = BABYLON.Vector3.Zero();
  32487. var ringFirstVertex = BABYLON.Vector3.Zero();
  32488. var ringFirstNormal = BABYLON.Vector3.Zero();
  32489. var quadNormal = BABYLON.Vector3.Zero();
  32490. var Y = BABYLON.Axis.Y;
  32491. // positions, normals, uvs
  32492. var i;
  32493. var j;
  32494. var r;
  32495. var ringIdx = 1;
  32496. var s = 1; // surface index
  32497. var cs = 0;
  32498. var v = 0;
  32499. for (i = 0; i <= subdivisions; i++) {
  32500. h = i / subdivisions;
  32501. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32502. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32503. for (r = 0; r < ringIdx; r++) {
  32504. if (hasRings) {
  32505. s += r;
  32506. }
  32507. if (enclose) {
  32508. s += 2 * r;
  32509. }
  32510. for (j = 0; j <= tessellation; j++) {
  32511. angle = j * angle_step;
  32512. // position
  32513. ringVertex.x = Math.cos(-angle) * radius;
  32514. ringVertex.y = -height / 2 + h * height;
  32515. ringVertex.z = Math.sin(-angle) * radius;
  32516. // normal
  32517. if (diameterTop === 0 && i === subdivisions) {
  32518. // if no top cap, reuse former normals
  32519. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32520. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32521. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32522. }
  32523. else {
  32524. ringNormal.x = ringVertex.x;
  32525. ringNormal.z = ringVertex.z;
  32526. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32527. ringNormal.normalize();
  32528. }
  32529. // keep first ring vertex values for enclose
  32530. if (j === 0) {
  32531. ringFirstVertex.copyFrom(ringVertex);
  32532. ringFirstNormal.copyFrom(ringNormal);
  32533. }
  32534. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32535. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32536. if (hasRings) {
  32537. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32538. }
  32539. else {
  32540. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32541. }
  32542. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32543. if (faceColors) {
  32544. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32545. }
  32546. }
  32547. // if enclose, add four vertices and their dedicated normals
  32548. if (arc !== 1 && enclose) {
  32549. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32550. positions.push(0, ringVertex.y, 0);
  32551. positions.push(0, ringVertex.y, 0);
  32552. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32553. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32554. quadNormal.normalize();
  32555. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32556. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32557. quadNormal.normalize();
  32558. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32559. if (hasRings) {
  32560. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32561. }
  32562. else {
  32563. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32564. }
  32565. uvs.push(faceUV[s + 1].x, v);
  32566. uvs.push(faceUV[s + 1].z, v);
  32567. if (hasRings) {
  32568. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32569. }
  32570. else {
  32571. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32572. }
  32573. uvs.push(faceUV[s + 2].x, v);
  32574. uvs.push(faceUV[s + 2].z, v);
  32575. if (faceColors) {
  32576. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32577. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32578. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32579. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32580. }
  32581. }
  32582. if (cs !== s) {
  32583. cs = s;
  32584. }
  32585. }
  32586. }
  32587. // indices
  32588. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32589. var s;
  32590. i = 0;
  32591. for (s = 0; s < subdivisions; s++) {
  32592. var i0 = 0;
  32593. var i1 = 0;
  32594. var i2 = 0;
  32595. var i3 = 0;
  32596. for (j = 0; j < tessellation; j++) {
  32597. i0 = i * (e + 1) + j;
  32598. i1 = (i + 1) * (e + 1) + j;
  32599. i2 = i * (e + 1) + (j + 1);
  32600. i3 = (i + 1) * (e + 1) + (j + 1);
  32601. indices.push(i0, i1, i2);
  32602. indices.push(i3, i2, i1);
  32603. }
  32604. if (arc !== 1 && enclose) {
  32605. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32606. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32607. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32608. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32609. }
  32610. i = (hasRings) ? (i + 2) : (i + 1);
  32611. }
  32612. // Caps
  32613. var createCylinderCap = function (isTop) {
  32614. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32615. if (radius === 0) {
  32616. return;
  32617. }
  32618. // Cap positions, normals & uvs
  32619. var angle;
  32620. var circleVector;
  32621. var i;
  32622. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32623. var c = null;
  32624. if (faceColors) {
  32625. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32626. }
  32627. // cap center
  32628. var vbase = positions.length / 3;
  32629. var offset = isTop ? height / 2 : -height / 2;
  32630. var center = new BABYLON.Vector3(0, offset, 0);
  32631. positions.push(center.x, center.y, center.z);
  32632. normals.push(0, isTop ? 1 : -1, 0);
  32633. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32634. if (c) {
  32635. colors.push(c.r, c.g, c.b, c.a);
  32636. }
  32637. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32638. for (i = 0; i <= tessellation; i++) {
  32639. angle = Math.PI * 2 * i * arc / tessellation;
  32640. var cos = Math.cos(-angle);
  32641. var sin = Math.sin(-angle);
  32642. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32643. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32644. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32645. normals.push(0, isTop ? 1 : -1, 0);
  32646. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32647. if (c) {
  32648. colors.push(c.r, c.g, c.b, c.a);
  32649. }
  32650. }
  32651. // Cap indices
  32652. for (i = 0; i < tessellation; i++) {
  32653. if (!isTop) {
  32654. indices.push(vbase);
  32655. indices.push(vbase + (i + 1));
  32656. indices.push(vbase + (i + 2));
  32657. }
  32658. else {
  32659. indices.push(vbase);
  32660. indices.push(vbase + (i + 2));
  32661. indices.push(vbase + (i + 1));
  32662. }
  32663. }
  32664. };
  32665. // add caps to geometry
  32666. createCylinderCap(false);
  32667. createCylinderCap(true);
  32668. // Sides
  32669. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32670. var vertexData = new VertexData();
  32671. vertexData.indices = indices;
  32672. vertexData.positions = positions;
  32673. vertexData.normals = normals;
  32674. vertexData.uvs = uvs;
  32675. if (faceColors) {
  32676. vertexData.colors = colors;
  32677. }
  32678. return vertexData;
  32679. };
  32680. /**
  32681. * Creates the VertexData of the Torus.
  32682. */
  32683. VertexData.CreateTorus = function (options) {
  32684. var indices = [];
  32685. var positions = [];
  32686. var normals = [];
  32687. var uvs = [];
  32688. var diameter = options.diameter || 1;
  32689. var thickness = options.thickness || 0.5;
  32690. var tessellation = options.tessellation || 16;
  32691. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32692. var stride = tessellation + 1;
  32693. for (var i = 0; i <= tessellation; i++) {
  32694. var u = i / tessellation;
  32695. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32696. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32697. for (var j = 0; j <= tessellation; j++) {
  32698. var v = 1 - j / tessellation;
  32699. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32700. var dx = Math.cos(innerAngle);
  32701. var dy = Math.sin(innerAngle);
  32702. // Create a vertex.
  32703. var normal = new BABYLON.Vector3(dx, dy, 0);
  32704. var position = normal.scale(thickness / 2);
  32705. var textureCoordinate = new BABYLON.Vector2(u, v);
  32706. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32707. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32708. positions.push(position.x, position.y, position.z);
  32709. normals.push(normal.x, normal.y, normal.z);
  32710. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32711. // And create indices for two triangles.
  32712. var nextI = (i + 1) % stride;
  32713. var nextJ = (j + 1) % stride;
  32714. indices.push(i * stride + j);
  32715. indices.push(i * stride + nextJ);
  32716. indices.push(nextI * stride + j);
  32717. indices.push(i * stride + nextJ);
  32718. indices.push(nextI * stride + nextJ);
  32719. indices.push(nextI * stride + j);
  32720. }
  32721. }
  32722. // Sides
  32723. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32724. // Result
  32725. var vertexData = new VertexData();
  32726. vertexData.indices = indices;
  32727. vertexData.positions = positions;
  32728. vertexData.normals = normals;
  32729. vertexData.uvs = uvs;
  32730. return vertexData;
  32731. };
  32732. /**
  32733. * Creates the VertexData of the LineSystem.
  32734. */
  32735. VertexData.CreateLineSystem = function (options) {
  32736. var indices = [];
  32737. var positions = [];
  32738. var lines = options.lines;
  32739. var colors = options.colors;
  32740. var vertexColors = [];
  32741. var idx = 0;
  32742. for (var l = 0; l < lines.length; l++) {
  32743. var points = lines[l];
  32744. for (var index = 0; index < points.length; index++) {
  32745. positions.push(points[index].x, points[index].y, points[index].z);
  32746. if (colors) {
  32747. var color = colors[l];
  32748. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  32749. }
  32750. if (index > 0) {
  32751. indices.push(idx - 1);
  32752. indices.push(idx);
  32753. }
  32754. idx++;
  32755. }
  32756. }
  32757. var vertexData = new VertexData();
  32758. vertexData.indices = indices;
  32759. vertexData.positions = positions;
  32760. if (colors) {
  32761. vertexData.colors = vertexColors;
  32762. }
  32763. return vertexData;
  32764. };
  32765. /**
  32766. * Create the VertexData of the DashedLines.
  32767. */
  32768. VertexData.CreateDashedLines = function (options) {
  32769. var dashSize = options.dashSize || 3;
  32770. var gapSize = options.gapSize || 1;
  32771. var dashNb = options.dashNb || 200;
  32772. var points = options.points;
  32773. var positions = new Array();
  32774. var indices = new Array();
  32775. var curvect = BABYLON.Vector3.Zero();
  32776. var lg = 0;
  32777. var nb = 0;
  32778. var shft = 0;
  32779. var dashshft = 0;
  32780. var curshft = 0;
  32781. var idx = 0;
  32782. var i = 0;
  32783. for (i = 0; i < points.length - 1; i++) {
  32784. points[i + 1].subtractToRef(points[i], curvect);
  32785. lg += curvect.length();
  32786. }
  32787. shft = lg / dashNb;
  32788. dashshft = dashSize * shft / (dashSize + gapSize);
  32789. for (i = 0; i < points.length - 1; i++) {
  32790. points[i + 1].subtractToRef(points[i], curvect);
  32791. nb = Math.floor(curvect.length() / shft);
  32792. curvect.normalize();
  32793. for (var j = 0; j < nb; j++) {
  32794. curshft = shft * j;
  32795. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  32796. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  32797. indices.push(idx, idx + 1);
  32798. idx += 2;
  32799. }
  32800. }
  32801. // Result
  32802. var vertexData = new VertexData();
  32803. vertexData.positions = positions;
  32804. vertexData.indices = indices;
  32805. return vertexData;
  32806. };
  32807. /**
  32808. * Creates the VertexData of the Ground.
  32809. */
  32810. VertexData.CreateGround = function (options) {
  32811. var indices = [];
  32812. var positions = [];
  32813. var normals = [];
  32814. var uvs = [];
  32815. var row, col;
  32816. var width = options.width || 1;
  32817. var height = options.height || 1;
  32818. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  32819. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  32820. for (row = 0; row <= subdivisionsY; row++) {
  32821. for (col = 0; col <= subdivisionsX; col++) {
  32822. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  32823. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32824. positions.push(position.x, position.y, position.z);
  32825. normals.push(normal.x, normal.y, normal.z);
  32826. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  32827. }
  32828. }
  32829. for (row = 0; row < subdivisionsY; row++) {
  32830. for (col = 0; col < subdivisionsX; col++) {
  32831. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32832. indices.push(col + 1 + row * (subdivisionsX + 1));
  32833. indices.push(col + row * (subdivisionsX + 1));
  32834. indices.push(col + (row + 1) * (subdivisionsX + 1));
  32835. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32836. indices.push(col + row * (subdivisionsX + 1));
  32837. }
  32838. }
  32839. // Result
  32840. var vertexData = new VertexData();
  32841. vertexData.indices = indices;
  32842. vertexData.positions = positions;
  32843. vertexData.normals = normals;
  32844. vertexData.uvs = uvs;
  32845. return vertexData;
  32846. };
  32847. /**
  32848. * Creates the VertexData of the TiledGround.
  32849. */
  32850. VertexData.CreateTiledGround = function (options) {
  32851. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  32852. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  32853. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  32854. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  32855. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  32856. var precision = options.precision || { w: 1, h: 1 };
  32857. var indices = new Array();
  32858. var positions = new Array();
  32859. var normals = new Array();
  32860. var uvs = new Array();
  32861. var row, col, tileRow, tileCol;
  32862. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  32863. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  32864. precision.w = (precision.w < 1) ? 1 : precision.w;
  32865. precision.h = (precision.h < 1) ? 1 : precision.h;
  32866. var tileSize = {
  32867. 'w': (xmax - xmin) / subdivisions.w,
  32868. 'h': (zmax - zmin) / subdivisions.h
  32869. };
  32870. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  32871. // Indices
  32872. var base = positions.length / 3;
  32873. var rowLength = precision.w + 1;
  32874. for (row = 0; row < precision.h; row++) {
  32875. for (col = 0; col < precision.w; col++) {
  32876. var square = [
  32877. base + col + row * rowLength,
  32878. base + (col + 1) + row * rowLength,
  32879. base + (col + 1) + (row + 1) * rowLength,
  32880. base + col + (row + 1) * rowLength
  32881. ];
  32882. indices.push(square[1]);
  32883. indices.push(square[2]);
  32884. indices.push(square[3]);
  32885. indices.push(square[0]);
  32886. indices.push(square[1]);
  32887. indices.push(square[3]);
  32888. }
  32889. }
  32890. // Position, normals and uvs
  32891. var position = BABYLON.Vector3.Zero();
  32892. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32893. for (row = 0; row <= precision.h; row++) {
  32894. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  32895. for (col = 0; col <= precision.w; col++) {
  32896. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  32897. position.y = 0;
  32898. positions.push(position.x, position.y, position.z);
  32899. normals.push(normal.x, normal.y, normal.z);
  32900. uvs.push(col / precision.w, row / precision.h);
  32901. }
  32902. }
  32903. }
  32904. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  32905. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  32906. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  32907. }
  32908. }
  32909. // Result
  32910. var vertexData = new VertexData();
  32911. vertexData.indices = indices;
  32912. vertexData.positions = positions;
  32913. vertexData.normals = normals;
  32914. vertexData.uvs = uvs;
  32915. return vertexData;
  32916. };
  32917. /**
  32918. * Creates the VertexData of the Ground designed from a heightmap.
  32919. */
  32920. VertexData.CreateGroundFromHeightMap = function (options) {
  32921. var indices = [];
  32922. var positions = [];
  32923. var normals = [];
  32924. var uvs = [];
  32925. var row, col;
  32926. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  32927. // Vertices
  32928. for (row = 0; row <= options.subdivisions; row++) {
  32929. for (col = 0; col <= options.subdivisions; col++) {
  32930. 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));
  32931. // Compute height
  32932. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  32933. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  32934. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  32935. var r = options.buffer[pos] / 255.0;
  32936. var g = options.buffer[pos + 1] / 255.0;
  32937. var b = options.buffer[pos + 2] / 255.0;
  32938. var gradient = r * filter.r + g * filter.g + b * filter.b;
  32939. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  32940. // Add vertex
  32941. positions.push(position.x, position.y, position.z);
  32942. normals.push(0, 0, 0);
  32943. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  32944. }
  32945. }
  32946. // Indices
  32947. for (row = 0; row < options.subdivisions; row++) {
  32948. for (col = 0; col < options.subdivisions; col++) {
  32949. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32950. indices.push(col + 1 + row * (options.subdivisions + 1));
  32951. indices.push(col + row * (options.subdivisions + 1));
  32952. indices.push(col + (row + 1) * (options.subdivisions + 1));
  32953. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32954. indices.push(col + row * (options.subdivisions + 1));
  32955. }
  32956. }
  32957. // Normals
  32958. VertexData.ComputeNormals(positions, indices, normals);
  32959. // Result
  32960. var vertexData = new VertexData();
  32961. vertexData.indices = indices;
  32962. vertexData.positions = positions;
  32963. vertexData.normals = normals;
  32964. vertexData.uvs = uvs;
  32965. return vertexData;
  32966. };
  32967. /**
  32968. * Creates the VertexData of the Plane.
  32969. */
  32970. VertexData.CreatePlane = function (options) {
  32971. var indices = [];
  32972. var positions = [];
  32973. var normals = [];
  32974. var uvs = [];
  32975. var width = options.width || options.size || 1;
  32976. var height = options.height || options.size || 1;
  32977. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32978. // Vertices
  32979. var halfWidth = width / 2.0;
  32980. var halfHeight = height / 2.0;
  32981. positions.push(-halfWidth, -halfHeight, 0);
  32982. normals.push(0, 0, -1.0);
  32983. uvs.push(0.0, 0.0);
  32984. positions.push(halfWidth, -halfHeight, 0);
  32985. normals.push(0, 0, -1.0);
  32986. uvs.push(1.0, 0.0);
  32987. positions.push(halfWidth, halfHeight, 0);
  32988. normals.push(0, 0, -1.0);
  32989. uvs.push(1.0, 1.0);
  32990. positions.push(-halfWidth, halfHeight, 0);
  32991. normals.push(0, 0, -1.0);
  32992. uvs.push(0.0, 1.0);
  32993. // Indices
  32994. indices.push(0);
  32995. indices.push(1);
  32996. indices.push(2);
  32997. indices.push(0);
  32998. indices.push(2);
  32999. indices.push(3);
  33000. // Sides
  33001. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33002. // Result
  33003. var vertexData = new VertexData();
  33004. vertexData.indices = indices;
  33005. vertexData.positions = positions;
  33006. vertexData.normals = normals;
  33007. vertexData.uvs = uvs;
  33008. return vertexData;
  33009. };
  33010. /**
  33011. * Creates the VertexData of the Disc or regular Polygon.
  33012. */
  33013. VertexData.CreateDisc = function (options) {
  33014. var positions = new Array();
  33015. var indices = new Array();
  33016. var normals = new Array();
  33017. var uvs = new Array();
  33018. var radius = options.radius || 0.5;
  33019. var tessellation = options.tessellation || 64;
  33020. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33021. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33022. // positions and uvs
  33023. positions.push(0, 0, 0); // disc center first
  33024. uvs.push(0.5, 0.5);
  33025. var theta = Math.PI * 2 * arc;
  33026. var step = theta / tessellation;
  33027. for (var a = 0; a < theta; a += step) {
  33028. var x = Math.cos(a);
  33029. var y = Math.sin(a);
  33030. var u = (x + 1) / 2;
  33031. var v = (1 - y) / 2;
  33032. positions.push(radius * x, radius * y, 0);
  33033. uvs.push(u, v);
  33034. }
  33035. if (arc === 1) {
  33036. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33037. uvs.push(uvs[2], uvs[3]);
  33038. }
  33039. //indices
  33040. var vertexNb = positions.length / 3;
  33041. for (var i = 1; i < vertexNb - 1; i++) {
  33042. indices.push(i + 1, 0, i);
  33043. }
  33044. // result
  33045. VertexData.ComputeNormals(positions, indices, normals);
  33046. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33047. var vertexData = new VertexData();
  33048. vertexData.indices = indices;
  33049. vertexData.positions = positions;
  33050. vertexData.normals = normals;
  33051. vertexData.uvs = uvs;
  33052. return vertexData;
  33053. };
  33054. /**
  33055. * Re-creates the VertexData of the Polygon for sideOrientation.
  33056. */
  33057. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33058. var faceUV = fUV || new Array(3);
  33059. var faceColors = fColors;
  33060. var colors = [];
  33061. // default face colors and UV if undefined
  33062. for (var f = 0; f < 3; f++) {
  33063. if (faceUV[f] === undefined) {
  33064. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33065. }
  33066. if (faceColors && faceColors[f] === undefined) {
  33067. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33068. }
  33069. }
  33070. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33071. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33072. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33073. var indices = polygon.getIndices();
  33074. // set face colours and textures
  33075. var idx = 0;
  33076. var face = 0;
  33077. for (var index = 0; index < normals.length; index += 3) {
  33078. //Edge Face no. 1
  33079. if (Math.abs(normals[index + 1]) < 0.001) {
  33080. face = 1;
  33081. }
  33082. //Top Face no. 0
  33083. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33084. face = 0;
  33085. }
  33086. //Bottom Face no. 2
  33087. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33088. face = 2;
  33089. }
  33090. idx = index / 3;
  33091. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33092. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33093. if (faceColors) {
  33094. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33095. }
  33096. }
  33097. // sides
  33098. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33099. // Result
  33100. var vertexData = new VertexData();
  33101. vertexData.indices = indices;
  33102. vertexData.positions = positions;
  33103. vertexData.normals = normals;
  33104. vertexData.uvs = uvs;
  33105. if (faceColors) {
  33106. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33107. vertexData.colors = totalColors;
  33108. }
  33109. return vertexData;
  33110. };
  33111. /**
  33112. * Creates the VertexData of the IcoSphere.
  33113. */
  33114. VertexData.CreateIcoSphere = function (options) {
  33115. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33116. var radius = options.radius || 1;
  33117. var flat = (options.flat === undefined) ? true : options.flat;
  33118. var subdivisions = options.subdivisions || 4;
  33119. var radiusX = options.radiusX || radius;
  33120. var radiusY = options.radiusY || radius;
  33121. var radiusZ = options.radiusZ || radius;
  33122. var t = (1 + Math.sqrt(5)) / 2;
  33123. // 12 vertex x,y,z
  33124. var ico_vertices = [
  33125. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33126. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33127. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33128. ];
  33129. // index of 3 vertex makes a face of icopshere
  33130. var ico_indices = [
  33131. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33132. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33133. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33134. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33135. ];
  33136. // vertex for uv have aliased position, not for UV
  33137. var vertices_unalias_id = [
  33138. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33139. // vertex alias
  33140. 0,
  33141. 2,
  33142. 3,
  33143. 3,
  33144. 3,
  33145. 4,
  33146. 7,
  33147. 8,
  33148. 9,
  33149. 9,
  33150. 10,
  33151. 11 // 23: B + 12
  33152. ];
  33153. // uv as integer step (not pixels !)
  33154. var ico_vertexuv = [
  33155. 5, 1, 3, 1, 6, 4, 0, 0,
  33156. 5, 3, 4, 2, 2, 2, 4, 0,
  33157. 2, 0, 1, 1, 6, 0, 6, 2,
  33158. // vertex alias (for same vertex on different faces)
  33159. 0, 4,
  33160. 3, 3,
  33161. 4, 4,
  33162. 3, 1,
  33163. 4, 2,
  33164. 4, 4,
  33165. 0, 2,
  33166. 1, 1,
  33167. 2, 2,
  33168. 3, 3,
  33169. 1, 3,
  33170. 2, 4 // 23: B + 12
  33171. ];
  33172. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33173. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33174. // First island of uv mapping
  33175. // v = 4h 3+ 2
  33176. // v = 3h 9+ 4
  33177. // v = 2h 9+ 5 B
  33178. // v = 1h 9 1 0
  33179. // v = 0h 3 8 7 A
  33180. // u = 0 1 2 3 4 5 6 *a
  33181. // Second island of uv mapping
  33182. // v = 4h 0+ B+ 4+
  33183. // v = 3h A+ 2+
  33184. // v = 2h 7+ 6 3+
  33185. // v = 1h 8+ 3+
  33186. // v = 0h
  33187. // u = 0 1 2 3 4 5 6 *a
  33188. // Face layout on texture UV mapping
  33189. // ============
  33190. // \ 4 /\ 16 / ======
  33191. // \ / \ / /\ 11 /
  33192. // \/ 7 \/ / \ /
  33193. // ======= / 10 \/
  33194. // /\ 17 /\ =======
  33195. // / \ / \ \ 15 /\
  33196. // / 8 \/ 12 \ \ / \
  33197. // ============ \/ 6 \
  33198. // \ 18 /\ ============
  33199. // \ / \ \ 5 /\ 0 /
  33200. // \/ 13 \ \ / \ /
  33201. // ======= \/ 1 \/
  33202. // =============
  33203. // /\ 19 /\ 2 /\
  33204. // / \ / \ / \
  33205. // / 14 \/ 9 \/ 3 \
  33206. // ===================
  33207. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33208. var ustep = 138 / 1024;
  33209. var vstep = 239 / 1024;
  33210. var uoffset = 60 / 1024;
  33211. var voffset = 26 / 1024;
  33212. // Second island should have margin, not to touch the first island
  33213. // avoid any borderline artefact in pixel rounding
  33214. var island_u_offset = -40 / 1024;
  33215. var island_v_offset = +20 / 1024;
  33216. // face is either island 0 or 1 :
  33217. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33218. var island = [
  33219. 0, 0, 0, 0, 1,
  33220. 0, 0, 1, 1, 0,
  33221. 0, 0, 1, 1, 0,
  33222. 0, 1, 1, 1, 0 // 15 - 19
  33223. ];
  33224. var indices = new Array();
  33225. var positions = new Array();
  33226. var normals = new Array();
  33227. var uvs = new Array();
  33228. var current_indice = 0;
  33229. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33230. var face_vertex_pos = new Array(3);
  33231. var face_vertex_uv = new Array(3);
  33232. var v012;
  33233. for (v012 = 0; v012 < 3; v012++) {
  33234. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33235. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33236. }
  33237. // create all with normals
  33238. for (var face = 0; face < 20; face++) {
  33239. // 3 vertex per face
  33240. for (v012 = 0; v012 < 3; v012++) {
  33241. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33242. var v_id = ico_indices[3 * face + v012];
  33243. // vertex have 3D position (x,y,z)
  33244. 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]);
  33245. // Normalize to get normal, then scale to radius
  33246. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33247. // uv Coordinates from vertex ID
  33248. 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);
  33249. }
  33250. // Subdivide the face (interpolate pos, norm, uv)
  33251. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33252. // - norm is linear interpolation of vertex corner normal
  33253. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33254. // - uv is linear interpolation
  33255. //
  33256. // Topology is as below for sub-divide by 2
  33257. // vertex shown as v0,v1,v2
  33258. // interp index is i1 to progress in range [v0,v1[
  33259. // interp index is i2 to progress in range [v0,v2[
  33260. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33261. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33262. //
  33263. //
  33264. // i2 v2
  33265. // ^ ^
  33266. // / / \
  33267. // / / \
  33268. // / / \
  33269. // / / (0,1) \
  33270. // / #---------\
  33271. // / / \ (0,0)'/ \
  33272. // / / \ / \
  33273. // / / \ / \
  33274. // / / (0,0) \ / (1,0) \
  33275. // / #---------#---------\
  33276. // v0 v1
  33277. //
  33278. // --------------------> i1
  33279. //
  33280. // interp of (i1,i2):
  33281. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33282. // along i1 : lerp(x0,x1, i1/(S-i2))
  33283. //
  33284. // centroid of triangle is needed to get help normal computation
  33285. // (c1,c2) are used for centroid location
  33286. var interp_vertex = function (i1, i2, c1, c2) {
  33287. // vertex is interpolated from
  33288. // - face_vertex_pos[0..2]
  33289. // - face_vertex_uv[0..2]
  33290. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33291. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33292. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33293. pos_interp.normalize();
  33294. var vertex_normal;
  33295. if (flat) {
  33296. // in flat mode, recalculate normal as face centroid normal
  33297. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33298. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33299. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33300. }
  33301. else {
  33302. // in smooth mode, recalculate normal from each single vertex position
  33303. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33304. }
  33305. // Vertex normal need correction due to X,Y,Z radius scaling
  33306. vertex_normal.x /= radiusX;
  33307. vertex_normal.y /= radiusY;
  33308. vertex_normal.z /= radiusZ;
  33309. vertex_normal.normalize();
  33310. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33311. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33312. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33313. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33314. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33315. uvs.push(uv_interp.x, uv_interp.y);
  33316. // push each vertex has member of a face
  33317. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33318. indices.push(current_indice);
  33319. current_indice++;
  33320. };
  33321. for (var i2 = 0; i2 < subdivisions; i2++) {
  33322. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33323. // face : (i1,i2) for /\ :
  33324. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33325. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33326. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33327. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33328. if (i1 + i2 + 1 < subdivisions) {
  33329. // face : (i1,i2)' for \/ :
  33330. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33331. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33332. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33333. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33334. }
  33335. }
  33336. }
  33337. }
  33338. // Sides
  33339. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33340. // Result
  33341. var vertexData = new VertexData();
  33342. vertexData.indices = indices;
  33343. vertexData.positions = positions;
  33344. vertexData.normals = normals;
  33345. vertexData.uvs = uvs;
  33346. return vertexData;
  33347. };
  33348. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33349. /**
  33350. * Creates the VertexData of the Polyhedron.
  33351. */
  33352. VertexData.CreatePolyhedron = function (options) {
  33353. // provided polyhedron types :
  33354. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33355. // 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)
  33356. var polyhedra = [];
  33357. 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]] };
  33358. 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]] };
  33359. polyhedra[2] = {
  33360. 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]],
  33361. 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]]
  33362. };
  33363. polyhedra[3] = {
  33364. 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]],
  33365. 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]]
  33366. };
  33367. polyhedra[4] = {
  33368. 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]],
  33369. 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]]
  33370. };
  33371. 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]] };
  33372. 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]] };
  33373. 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]] };
  33374. 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]] };
  33375. 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]] };
  33376. 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]] };
  33377. 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]] };
  33378. 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]] };
  33379. 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]] };
  33380. polyhedra[14] = {
  33381. 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]],
  33382. 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]]
  33383. };
  33384. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33385. var size = options.size;
  33386. var sizeX = options.sizeX || size || 1;
  33387. var sizeY = options.sizeY || size || 1;
  33388. var sizeZ = options.sizeZ || size || 1;
  33389. var data = options.custom || polyhedra[type];
  33390. var nbfaces = data.face.length;
  33391. var faceUV = options.faceUV || new Array(nbfaces);
  33392. var faceColors = options.faceColors;
  33393. var flat = (options.flat === undefined) ? true : options.flat;
  33394. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33395. var positions = new Array();
  33396. var indices = new Array();
  33397. var normals = new Array();
  33398. var uvs = new Array();
  33399. var colors = new Array();
  33400. var index = 0;
  33401. var faceIdx = 0; // face cursor in the array "indexes"
  33402. var indexes = new Array();
  33403. var i = 0;
  33404. var f = 0;
  33405. var u, v, ang, x, y, tmp;
  33406. // default face colors and UV if undefined
  33407. if (flat) {
  33408. for (f = 0; f < nbfaces; f++) {
  33409. if (faceColors && faceColors[f] === undefined) {
  33410. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33411. }
  33412. if (faceUV && faceUV[f] === undefined) {
  33413. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33414. }
  33415. }
  33416. }
  33417. if (!flat) {
  33418. for (i = 0; i < data.vertex.length; i++) {
  33419. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33420. uvs.push(0, 0);
  33421. }
  33422. for (f = 0; f < nbfaces; f++) {
  33423. for (i = 0; i < data.face[f].length - 2; i++) {
  33424. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33425. }
  33426. }
  33427. }
  33428. else {
  33429. for (f = 0; f < nbfaces; f++) {
  33430. var fl = data.face[f].length; // number of vertices of the current face
  33431. ang = 2 * Math.PI / fl;
  33432. x = 0.5 * Math.tan(ang / 2);
  33433. y = 0.5;
  33434. // positions, uvs, colors
  33435. for (i = 0; i < fl; i++) {
  33436. // positions
  33437. 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);
  33438. indexes.push(index);
  33439. index++;
  33440. // uvs
  33441. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33442. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33443. uvs.push(u, v);
  33444. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33445. y = x * Math.sin(ang) + y * Math.cos(ang);
  33446. x = tmp;
  33447. // colors
  33448. if (faceColors) {
  33449. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33450. }
  33451. }
  33452. // indices from indexes
  33453. for (i = 0; i < fl - 2; i++) {
  33454. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33455. }
  33456. faceIdx += fl;
  33457. }
  33458. }
  33459. VertexData.ComputeNormals(positions, indices, normals);
  33460. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33461. var vertexData = new VertexData();
  33462. vertexData.positions = positions;
  33463. vertexData.indices = indices;
  33464. vertexData.normals = normals;
  33465. vertexData.uvs = uvs;
  33466. if (faceColors && flat) {
  33467. vertexData.colors = colors;
  33468. }
  33469. return vertexData;
  33470. };
  33471. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33472. /**
  33473. * Creates the VertexData of the Torus Knot.
  33474. */
  33475. VertexData.CreateTorusKnot = function (options) {
  33476. var indices = new Array();
  33477. var positions = new Array();
  33478. var normals = new Array();
  33479. var uvs = new Array();
  33480. var radius = options.radius || 2;
  33481. var tube = options.tube || 0.5;
  33482. var radialSegments = options.radialSegments || 32;
  33483. var tubularSegments = options.tubularSegments || 32;
  33484. var p = options.p || 2;
  33485. var q = options.q || 3;
  33486. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33487. // Helper
  33488. var getPos = function (angle) {
  33489. var cu = Math.cos(angle);
  33490. var su = Math.sin(angle);
  33491. var quOverP = q / p * angle;
  33492. var cs = Math.cos(quOverP);
  33493. var tx = radius * (2 + cs) * 0.5 * cu;
  33494. var ty = radius * (2 + cs) * su * 0.5;
  33495. var tz = radius * Math.sin(quOverP) * 0.5;
  33496. return new BABYLON.Vector3(tx, ty, tz);
  33497. };
  33498. // Vertices
  33499. var i;
  33500. var j;
  33501. for (i = 0; i <= radialSegments; i++) {
  33502. var modI = i % radialSegments;
  33503. var u = modI / radialSegments * 2 * p * Math.PI;
  33504. var p1 = getPos(u);
  33505. var p2 = getPos(u + 0.01);
  33506. var tang = p2.subtract(p1);
  33507. var n = p2.add(p1);
  33508. var bitan = BABYLON.Vector3.Cross(tang, n);
  33509. n = BABYLON.Vector3.Cross(bitan, tang);
  33510. bitan.normalize();
  33511. n.normalize();
  33512. for (j = 0; j < tubularSegments; j++) {
  33513. var modJ = j % tubularSegments;
  33514. var v = modJ / tubularSegments * 2 * Math.PI;
  33515. var cx = -tube * Math.cos(v);
  33516. var cy = tube * Math.sin(v);
  33517. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33518. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33519. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33520. uvs.push(i / radialSegments);
  33521. uvs.push(j / tubularSegments);
  33522. }
  33523. }
  33524. for (i = 0; i < radialSegments; i++) {
  33525. for (j = 0; j < tubularSegments; j++) {
  33526. var jNext = (j + 1) % tubularSegments;
  33527. var a = i * tubularSegments + j;
  33528. var b = (i + 1) * tubularSegments + j;
  33529. var c = (i + 1) * tubularSegments + jNext;
  33530. var d = i * tubularSegments + jNext;
  33531. indices.push(d);
  33532. indices.push(b);
  33533. indices.push(a);
  33534. indices.push(d);
  33535. indices.push(c);
  33536. indices.push(b);
  33537. }
  33538. }
  33539. // Normals
  33540. VertexData.ComputeNormals(positions, indices, normals);
  33541. // Sides
  33542. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33543. // Result
  33544. var vertexData = new VertexData();
  33545. vertexData.indices = indices;
  33546. vertexData.positions = positions;
  33547. vertexData.normals = normals;
  33548. vertexData.uvs = uvs;
  33549. return vertexData;
  33550. };
  33551. // Tools
  33552. /**
  33553. * @param {any} - positions (number[] or Float32Array)
  33554. * @param {any} - indices (number[] or Uint16Array)
  33555. * @param {any} - normals (number[] or Float32Array)
  33556. * options (optional) :
  33557. * facetPositions : optional array of facet positions (vector3)
  33558. * facetNormals : optional array of facet normals (vector3)
  33559. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33560. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33561. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33562. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33563. * bInfo : optional bounding info, required for facetPartitioning computation
  33564. * useRightHandedSystem: optional boolean to for right handed system computation
  33565. * depthSort : optional boolean to enable the facet depth sort computation
  33566. * distanceTo : optional Vector3 to compute the facet depth from this location
  33567. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33568. */
  33569. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33570. // temporary scalar variables
  33571. var index = 0; // facet index
  33572. var p1p2x = 0.0; // p1p2 vector x coordinate
  33573. var p1p2y = 0.0; // p1p2 vector y coordinate
  33574. var p1p2z = 0.0; // p1p2 vector z coordinate
  33575. var p3p2x = 0.0; // p3p2 vector x coordinate
  33576. var p3p2y = 0.0; // p3p2 vector y coordinate
  33577. var p3p2z = 0.0; // p3p2 vector z coordinate
  33578. var faceNormalx = 0.0; // facet normal x coordinate
  33579. var faceNormaly = 0.0; // facet normal y coordinate
  33580. var faceNormalz = 0.0; // facet normal z coordinate
  33581. var length = 0.0; // facet normal length before normalization
  33582. var v1x = 0; // vector1 x index in the positions array
  33583. var v1y = 0; // vector1 y index in the positions array
  33584. var v1z = 0; // vector1 z index in the positions array
  33585. var v2x = 0; // vector2 x index in the positions array
  33586. var v2y = 0; // vector2 y index in the positions array
  33587. var v2z = 0; // vector2 z index in the positions array
  33588. var v3x = 0; // vector3 x index in the positions array
  33589. var v3y = 0; // vector3 y index in the positions array
  33590. var v3z = 0; // vector3 z index in the positions array
  33591. var computeFacetNormals = false;
  33592. var computeFacetPositions = false;
  33593. var computeFacetPartitioning = false;
  33594. var computeDepthSort = false;
  33595. var faceNormalSign = 1;
  33596. var ratio = 0;
  33597. var distanceTo = null;
  33598. if (options) {
  33599. computeFacetNormals = (options.facetNormals) ? true : false;
  33600. computeFacetPositions = (options.facetPositions) ? true : false;
  33601. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33602. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33603. ratio = options.ratio || 0;
  33604. computeDepthSort = (options.depthSort) ? true : false;
  33605. distanceTo = (options.distanceTo);
  33606. if (computeDepthSort) {
  33607. if (distanceTo === undefined) {
  33608. distanceTo = BABYLON.Vector3.Zero();
  33609. }
  33610. var depthSortedFacets = options.depthSortedFacets;
  33611. }
  33612. }
  33613. // facetPartitioning reinit if needed
  33614. var xSubRatio = 0;
  33615. var ySubRatio = 0;
  33616. var zSubRatio = 0;
  33617. var subSq = 0;
  33618. if (computeFacetPartitioning && options && options.bbSize) {
  33619. var ox = 0; // X partitioning index for facet position
  33620. var oy = 0; // Y partinioning index for facet position
  33621. var oz = 0; // Z partinioning index for facet position
  33622. var b1x = 0; // X partitioning index for facet v1 vertex
  33623. var b1y = 0; // Y partitioning index for facet v1 vertex
  33624. var b1z = 0; // z partitioning index for facet v1 vertex
  33625. var b2x = 0; // X partitioning index for facet v2 vertex
  33626. var b2y = 0; // Y partitioning index for facet v2 vertex
  33627. var b2z = 0; // Z partitioning index for facet v2 vertex
  33628. var b3x = 0; // X partitioning index for facet v3 vertex
  33629. var b3y = 0; // Y partitioning index for facet v3 vertex
  33630. var b3z = 0; // Z partitioning index for facet v3 vertex
  33631. var block_idx_o = 0; // facet barycenter block index
  33632. var block_idx_v1 = 0; // v1 vertex block index
  33633. var block_idx_v2 = 0; // v2 vertex block index
  33634. var block_idx_v3 = 0; // v3 vertex block index
  33635. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33636. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33637. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33638. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33639. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33640. subSq = options.subDiv.max * options.subDiv.max;
  33641. options.facetPartitioning.length = 0;
  33642. }
  33643. // reset the normals
  33644. for (index = 0; index < positions.length; index++) {
  33645. normals[index] = 0.0;
  33646. }
  33647. // Loop : 1 indice triplet = 1 facet
  33648. var nbFaces = (indices.length / 3) | 0;
  33649. for (index = 0; index < nbFaces; index++) {
  33650. // get the indexes of the coordinates of each vertex of the facet
  33651. v1x = indices[index * 3] * 3;
  33652. v1y = v1x + 1;
  33653. v1z = v1x + 2;
  33654. v2x = indices[index * 3 + 1] * 3;
  33655. v2y = v2x + 1;
  33656. v2z = v2x + 2;
  33657. v3x = indices[index * 3 + 2] * 3;
  33658. v3y = v3x + 1;
  33659. v3z = v3x + 2;
  33660. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  33661. p1p2y = positions[v1y] - positions[v2y];
  33662. p1p2z = positions[v1z] - positions[v2z];
  33663. p3p2x = positions[v3x] - positions[v2x];
  33664. p3p2y = positions[v3y] - positions[v2y];
  33665. p3p2z = positions[v3z] - positions[v2z];
  33666. // compute the face normal with the cross product
  33667. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  33668. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  33669. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  33670. // normalize this normal and store it in the array facetData
  33671. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33672. length = (length === 0) ? 1.0 : length;
  33673. faceNormalx /= length;
  33674. faceNormaly /= length;
  33675. faceNormalz /= length;
  33676. if (computeFacetNormals && options) {
  33677. options.facetNormals[index].x = faceNormalx;
  33678. options.facetNormals[index].y = faceNormaly;
  33679. options.facetNormals[index].z = faceNormalz;
  33680. }
  33681. if (computeFacetPositions && options) {
  33682. // compute and the facet barycenter coordinates in the array facetPositions
  33683. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  33684. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  33685. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  33686. }
  33687. if (computeFacetPartitioning && options) {
  33688. // store the facet indexes in arrays in the main facetPartitioning array :
  33689. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  33690. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  33691. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  33692. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  33693. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33694. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33695. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33696. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33697. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33698. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33699. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33700. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33701. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33702. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  33703. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  33704. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  33705. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  33706. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  33707. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  33708. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  33709. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  33710. // push each facet index in each block containing the vertex
  33711. options.facetPartitioning[block_idx_v1].push(index);
  33712. if (block_idx_v2 != block_idx_v1) {
  33713. options.facetPartitioning[block_idx_v2].push(index);
  33714. }
  33715. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  33716. options.facetPartitioning[block_idx_v3].push(index);
  33717. }
  33718. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  33719. options.facetPartitioning[block_idx_o].push(index);
  33720. }
  33721. }
  33722. if (computeDepthSort && options && options.facetPositions) {
  33723. var dsf = depthSortedFacets[index];
  33724. dsf.ind = index * 3;
  33725. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  33726. }
  33727. // compute the normals anyway
  33728. normals[v1x] += faceNormalx; // accumulate all the normals per face
  33729. normals[v1y] += faceNormaly;
  33730. normals[v1z] += faceNormalz;
  33731. normals[v2x] += faceNormalx;
  33732. normals[v2y] += faceNormaly;
  33733. normals[v2z] += faceNormalz;
  33734. normals[v3x] += faceNormalx;
  33735. normals[v3y] += faceNormaly;
  33736. normals[v3z] += faceNormalz;
  33737. }
  33738. // last normalization of each normal
  33739. for (index = 0; index < normals.length / 3; index++) {
  33740. faceNormalx = normals[index * 3];
  33741. faceNormaly = normals[index * 3 + 1];
  33742. faceNormalz = normals[index * 3 + 2];
  33743. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33744. length = (length === 0) ? 1.0 : length;
  33745. faceNormalx /= length;
  33746. faceNormaly /= length;
  33747. faceNormalz /= length;
  33748. normals[index * 3] = faceNormalx;
  33749. normals[index * 3 + 1] = faceNormaly;
  33750. normals[index * 3 + 2] = faceNormalz;
  33751. }
  33752. };
  33753. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  33754. var li = indices.length;
  33755. var ln = normals.length;
  33756. var i;
  33757. var n;
  33758. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33759. switch (sideOrientation) {
  33760. case BABYLON.Mesh.FRONTSIDE:
  33761. // nothing changed
  33762. break;
  33763. case BABYLON.Mesh.BACKSIDE:
  33764. var tmp;
  33765. // indices
  33766. for (i = 0; i < li; i += 3) {
  33767. tmp = indices[i];
  33768. indices[i] = indices[i + 2];
  33769. indices[i + 2] = tmp;
  33770. }
  33771. // normals
  33772. for (n = 0; n < ln; n++) {
  33773. normals[n] = -normals[n];
  33774. }
  33775. break;
  33776. case BABYLON.Mesh.DOUBLESIDE:
  33777. // positions
  33778. var lp = positions.length;
  33779. var l = lp / 3;
  33780. for (var p = 0; p < lp; p++) {
  33781. positions[lp + p] = positions[p];
  33782. }
  33783. // indices
  33784. for (i = 0; i < li; i += 3) {
  33785. indices[i + li] = indices[i + 2] + l;
  33786. indices[i + 1 + li] = indices[i + 1] + l;
  33787. indices[i + 2 + li] = indices[i] + l;
  33788. }
  33789. // normals
  33790. for (n = 0; n < ln; n++) {
  33791. normals[ln + n] = -normals[n];
  33792. }
  33793. // uvs
  33794. var lu = uvs.length;
  33795. var u = 0;
  33796. for (u = 0; u < lu; u++) {
  33797. uvs[u + lu] = uvs[u];
  33798. }
  33799. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33800. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33801. u = 0;
  33802. for (i = 0; i < lu / 2; i++) {
  33803. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  33804. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  33805. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  33806. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  33807. u += 2;
  33808. }
  33809. break;
  33810. }
  33811. };
  33812. /**
  33813. * Creates a new VertexData from the imported parameters.
  33814. */
  33815. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  33816. var vertexData = new VertexData();
  33817. // positions
  33818. var positions = parsedVertexData.positions;
  33819. if (positions) {
  33820. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  33821. }
  33822. // normals
  33823. var normals = parsedVertexData.normals;
  33824. if (normals) {
  33825. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  33826. }
  33827. // tangents
  33828. var tangents = parsedVertexData.tangents;
  33829. if (tangents) {
  33830. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  33831. }
  33832. // uvs
  33833. var uvs = parsedVertexData.uvs;
  33834. if (uvs) {
  33835. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  33836. }
  33837. // uv2s
  33838. var uv2s = parsedVertexData.uv2s;
  33839. if (uv2s) {
  33840. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  33841. }
  33842. // uv3s
  33843. var uv3s = parsedVertexData.uv3s;
  33844. if (uv3s) {
  33845. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  33846. }
  33847. // uv4s
  33848. var uv4s = parsedVertexData.uv4s;
  33849. if (uv4s) {
  33850. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  33851. }
  33852. // uv5s
  33853. var uv5s = parsedVertexData.uv5s;
  33854. if (uv5s) {
  33855. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  33856. }
  33857. // uv6s
  33858. var uv6s = parsedVertexData.uv6s;
  33859. if (uv6s) {
  33860. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  33861. }
  33862. // colors
  33863. var colors = parsedVertexData.colors;
  33864. if (colors) {
  33865. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  33866. }
  33867. // matricesIndices
  33868. var matricesIndices = parsedVertexData.matricesIndices;
  33869. if (matricesIndices) {
  33870. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  33871. }
  33872. // matricesWeights
  33873. var matricesWeights = parsedVertexData.matricesWeights;
  33874. if (matricesWeights) {
  33875. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  33876. }
  33877. // indices
  33878. var indices = parsedVertexData.indices;
  33879. if (indices) {
  33880. vertexData.indices = indices;
  33881. }
  33882. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  33883. };
  33884. return VertexData;
  33885. }());
  33886. BABYLON.VertexData = VertexData;
  33887. })(BABYLON || (BABYLON = {}));
  33888. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  33889. var BABYLON;
  33890. (function (BABYLON) {
  33891. /**
  33892. * Class used to store geometry data (vertex buffers + index buffer)
  33893. */
  33894. var Geometry = /** @class */ (function () {
  33895. /**
  33896. * Creates a new geometry
  33897. * @param id defines the unique ID
  33898. * @param scene defines the hosting scene
  33899. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  33900. * @param updatable defines if geometry must be updatable (false by default)
  33901. * @param mesh defines the mesh that will be associated with the geometry
  33902. */
  33903. function Geometry(id, scene, vertexData, updatable, mesh) {
  33904. if (updatable === void 0) { updatable = false; }
  33905. if (mesh === void 0) { mesh = null; }
  33906. /**
  33907. * Gets the delay loading state of the geometry (none by default which means not delayed)
  33908. */
  33909. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33910. this._totalVertices = 0;
  33911. this._isDisposed = false;
  33912. this._indexBufferIsUpdatable = false;
  33913. this.id = id;
  33914. this._engine = scene.getEngine();
  33915. this._meshes = [];
  33916. this._scene = scene;
  33917. //Init vertex buffer cache
  33918. this._vertexBuffers = {};
  33919. this._indices = [];
  33920. this._updatable = updatable;
  33921. // vertexData
  33922. if (vertexData) {
  33923. this.setAllVerticesData(vertexData, updatable);
  33924. }
  33925. else {
  33926. this._totalVertices = 0;
  33927. this._indices = [];
  33928. }
  33929. if (this._engine.getCaps().vertexArrayObject) {
  33930. this._vertexArrayObjects = {};
  33931. }
  33932. // applyToMesh
  33933. if (mesh) {
  33934. if (mesh.getClassName() === "LinesMesh") {
  33935. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  33936. this.updateExtend();
  33937. }
  33938. this.applyToMesh(mesh);
  33939. mesh.computeWorldMatrix(true);
  33940. }
  33941. }
  33942. Object.defineProperty(Geometry.prototype, "boundingBias", {
  33943. /**
  33944. * 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
  33945. */
  33946. get: function () {
  33947. return this._boundingBias;
  33948. },
  33949. /**
  33950. * 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
  33951. */
  33952. set: function (value) {
  33953. if (this._boundingBias && this._boundingBias.equals(value)) {
  33954. return;
  33955. }
  33956. this._boundingBias = value.clone();
  33957. this.updateBoundingInfo(true, null);
  33958. },
  33959. enumerable: true,
  33960. configurable: true
  33961. });
  33962. /**
  33963. * Static function used to attach a new empty geometry to a mesh
  33964. * @param mesh defines the mesh to attach the geometry to
  33965. * @returns the new {BABYLON.Geometry}
  33966. */
  33967. Geometry.CreateGeometryForMesh = function (mesh) {
  33968. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  33969. geometry.applyToMesh(mesh);
  33970. return geometry;
  33971. };
  33972. Object.defineProperty(Geometry.prototype, "extend", {
  33973. /**
  33974. * Gets the current extend of the geometry
  33975. */
  33976. get: function () {
  33977. return this._extend;
  33978. },
  33979. enumerable: true,
  33980. configurable: true
  33981. });
  33982. /**
  33983. * Gets the hosting scene
  33984. * @returns the hosting {BABYLON.Scene}
  33985. */
  33986. Geometry.prototype.getScene = function () {
  33987. return this._scene;
  33988. };
  33989. /**
  33990. * Gets the hosting engine
  33991. * @returns the hosting {BABYLON.Engine}
  33992. */
  33993. Geometry.prototype.getEngine = function () {
  33994. return this._engine;
  33995. };
  33996. /**
  33997. * Defines if the geometry is ready to use
  33998. * @returns true if the geometry is ready to be used
  33999. */
  34000. Geometry.prototype.isReady = function () {
  34001. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34002. };
  34003. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34004. /**
  34005. * Gets a value indicating that the geometry should not be serialized
  34006. */
  34007. get: function () {
  34008. for (var index = 0; index < this._meshes.length; index++) {
  34009. if (!this._meshes[index].doNotSerialize) {
  34010. return false;
  34011. }
  34012. }
  34013. return true;
  34014. },
  34015. enumerable: true,
  34016. configurable: true
  34017. });
  34018. /** @ignore */
  34019. Geometry.prototype._rebuild = function () {
  34020. if (this._vertexArrayObjects) {
  34021. this._vertexArrayObjects = {};
  34022. }
  34023. // Index buffer
  34024. if (this._meshes.length !== 0 && this._indices) {
  34025. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34026. }
  34027. // Vertex buffers
  34028. for (var key in this._vertexBuffers) {
  34029. var vertexBuffer = this._vertexBuffers[key];
  34030. vertexBuffer._rebuild();
  34031. }
  34032. };
  34033. /**
  34034. * Affects all gemetry data in one call
  34035. * @param vertexData defines the geometry data
  34036. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34037. */
  34038. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34039. vertexData.applyToGeometry(this, updatable);
  34040. this.notifyUpdate();
  34041. };
  34042. /**
  34043. * Set specific vertex data
  34044. * @param kind defines the data kind (Position, normal, etc...)
  34045. * @param data defines the vertex data to use
  34046. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34047. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34048. */
  34049. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34050. if (updatable === void 0) { updatable = false; }
  34051. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34052. this.setVerticesBuffer(buffer);
  34053. };
  34054. /**
  34055. * Removes a specific vertex data
  34056. * @param kind defines the data kind (Position, normal, etc...)
  34057. */
  34058. Geometry.prototype.removeVerticesData = function (kind) {
  34059. if (this._vertexBuffers[kind]) {
  34060. this._vertexBuffers[kind].dispose();
  34061. delete this._vertexBuffers[kind];
  34062. }
  34063. };
  34064. /**
  34065. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34066. * @param buffer defines the vertex buffer to use
  34067. */
  34068. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34069. var kind = buffer.getKind();
  34070. if (this._vertexBuffers[kind]) {
  34071. this._vertexBuffers[kind].dispose();
  34072. }
  34073. this._vertexBuffers[kind] = buffer;
  34074. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34075. var data = buffer.getData();
  34076. var stride = buffer.getStrideSize();
  34077. this._totalVertices = data.length / stride;
  34078. this.updateExtend(data, stride);
  34079. this._resetPointsArrayCache();
  34080. var meshes = this._meshes;
  34081. var numOfMeshes = meshes.length;
  34082. for (var index = 0; index < numOfMeshes; index++) {
  34083. var mesh = meshes[index];
  34084. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34085. mesh._createGlobalSubMesh(false);
  34086. mesh.computeWorldMatrix(true);
  34087. }
  34088. }
  34089. this.notifyUpdate(kind);
  34090. if (this._vertexArrayObjects) {
  34091. this._disposeVertexArrayObjects();
  34092. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34093. }
  34094. };
  34095. /**
  34096. * Update a specific vertex buffer
  34097. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34098. * It will do nothing if the buffer is not updatable
  34099. * @param kind defines the data kind (Position, normal, etc...)
  34100. * @param data defines the data to use
  34101. * @param offset defines the offset in the target buffer where to store the data
  34102. */
  34103. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34104. var vertexBuffer = this.getVertexBuffer(kind);
  34105. if (!vertexBuffer) {
  34106. return;
  34107. }
  34108. vertexBuffer.updateDirectly(data, offset);
  34109. this.notifyUpdate(kind);
  34110. };
  34111. /**
  34112. * Update a specific vertex buffer
  34113. * This function will create a new buffer if the current one is not updatable
  34114. * @param kind defines the data kind (Position, normal, etc...)
  34115. * @param data defines the data to use
  34116. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34117. */
  34118. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34119. if (updateExtends === void 0) { updateExtends = false; }
  34120. var vertexBuffer = this.getVertexBuffer(kind);
  34121. if (!vertexBuffer) {
  34122. return;
  34123. }
  34124. vertexBuffer.update(data);
  34125. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34126. var stride = vertexBuffer.getStrideSize();
  34127. this._totalVertices = data.length / stride;
  34128. this.updateBoundingInfo(updateExtends, data);
  34129. }
  34130. this.notifyUpdate(kind);
  34131. };
  34132. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34133. if (updateExtends) {
  34134. this.updateExtend(data);
  34135. }
  34136. var meshes = this._meshes;
  34137. var numOfMeshes = meshes.length;
  34138. this._resetPointsArrayCache();
  34139. for (var index = 0; index < numOfMeshes; index++) {
  34140. var mesh = meshes[index];
  34141. if (updateExtends) {
  34142. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34143. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34144. var subMesh = mesh.subMeshes[subIndex];
  34145. subMesh.refreshBoundingInfo();
  34146. }
  34147. }
  34148. }
  34149. };
  34150. /** @ignore */
  34151. Geometry.prototype._bind = function (effect, indexToBind) {
  34152. if (!effect) {
  34153. return;
  34154. }
  34155. if (indexToBind === undefined) {
  34156. indexToBind = this._indexBuffer;
  34157. }
  34158. var vbs = this.getVertexBuffers();
  34159. if (!vbs) {
  34160. return;
  34161. }
  34162. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34163. this._engine.bindBuffers(vbs, indexToBind, effect);
  34164. return;
  34165. }
  34166. // Using VAO
  34167. if (!this._vertexArrayObjects[effect.key]) {
  34168. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34169. }
  34170. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34171. };
  34172. /**
  34173. * Gets total number of vertices
  34174. * @returns the total number of vertices
  34175. */
  34176. Geometry.prototype.getTotalVertices = function () {
  34177. if (!this.isReady()) {
  34178. return 0;
  34179. }
  34180. return this._totalVertices;
  34181. };
  34182. /**
  34183. * Gets a specific vertex data attached to this geometry
  34184. * @param kind defines the data kind (Position, normal, etc...)
  34185. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34186. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34187. * @returns a float array containing vertex data
  34188. */
  34189. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34190. var vertexBuffer = this.getVertexBuffer(kind);
  34191. if (!vertexBuffer) {
  34192. return null;
  34193. }
  34194. var orig = vertexBuffer.getData();
  34195. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34196. return orig;
  34197. }
  34198. else {
  34199. var len = orig.length;
  34200. var copy = [];
  34201. for (var i = 0; i < len; i++) {
  34202. copy.push(orig[i]);
  34203. }
  34204. return copy;
  34205. }
  34206. };
  34207. /**
  34208. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34209. * @param kind defines the data kind (Position, normal, etc...)
  34210. * @returns true if the vertex buffer with the specified kind is updatable
  34211. */
  34212. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34213. var vb = this._vertexBuffers[kind];
  34214. if (!vb) {
  34215. return false;
  34216. }
  34217. return vb.isUpdatable();
  34218. };
  34219. /**
  34220. * Gets a specific vertex buffer
  34221. * @param kind defines the data kind (Position, normal, etc...)
  34222. * @returns a {BABYLON.VertexBuffer}
  34223. */
  34224. Geometry.prototype.getVertexBuffer = function (kind) {
  34225. if (!this.isReady()) {
  34226. return null;
  34227. }
  34228. return this._vertexBuffers[kind];
  34229. };
  34230. /**
  34231. * Returns all vertex buffers
  34232. * @return an object holding all vertex buffers indexed by kind
  34233. */
  34234. Geometry.prototype.getVertexBuffers = function () {
  34235. if (!this.isReady()) {
  34236. return null;
  34237. }
  34238. return this._vertexBuffers;
  34239. };
  34240. /**
  34241. * Gets a boolean indicating if specific vertex buffer is present
  34242. * @param kind defines the data kind (Position, normal, etc...)
  34243. * @returns true if data is present
  34244. */
  34245. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34246. if (!this._vertexBuffers) {
  34247. if (this._delayInfo) {
  34248. return this._delayInfo.indexOf(kind) !== -1;
  34249. }
  34250. return false;
  34251. }
  34252. return this._vertexBuffers[kind] !== undefined;
  34253. };
  34254. /**
  34255. * Gets a list of all attached data kinds (Position, normal, etc...)
  34256. * @returns a list of string containing all kinds
  34257. */
  34258. Geometry.prototype.getVerticesDataKinds = function () {
  34259. var result = [];
  34260. var kind;
  34261. if (!this._vertexBuffers && this._delayInfo) {
  34262. for (kind in this._delayInfo) {
  34263. result.push(kind);
  34264. }
  34265. }
  34266. else {
  34267. for (kind in this._vertexBuffers) {
  34268. result.push(kind);
  34269. }
  34270. }
  34271. return result;
  34272. };
  34273. /**
  34274. * Update index buffer
  34275. * @param indices defines the indices to store in the index buffer
  34276. * @param offset defines the offset in the target buffer where to store the data
  34277. */
  34278. Geometry.prototype.updateIndices = function (indices, offset) {
  34279. if (!this._indexBuffer) {
  34280. return;
  34281. }
  34282. if (!this._indexBufferIsUpdatable) {
  34283. this.setIndices(indices, null, true);
  34284. }
  34285. else {
  34286. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34287. }
  34288. };
  34289. /**
  34290. * Creates a new index buffer
  34291. * @param indices defines the indices to store in the index buffer
  34292. * @param totalVertices defines the total number of vertices (could be null)
  34293. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34294. */
  34295. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34296. if (totalVertices === void 0) { totalVertices = null; }
  34297. if (updatable === void 0) { updatable = false; }
  34298. if (this._indexBuffer) {
  34299. this._engine._releaseBuffer(this._indexBuffer);
  34300. }
  34301. this._disposeVertexArrayObjects();
  34302. this._indices = indices;
  34303. this._indexBufferIsUpdatable = updatable;
  34304. if (this._meshes.length !== 0 && this._indices) {
  34305. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34306. }
  34307. if (totalVertices != undefined) {
  34308. this._totalVertices = totalVertices;
  34309. }
  34310. var meshes = this._meshes;
  34311. var numOfMeshes = meshes.length;
  34312. for (var index = 0; index < numOfMeshes; index++) {
  34313. meshes[index]._createGlobalSubMesh(true);
  34314. }
  34315. this.notifyUpdate();
  34316. };
  34317. /**
  34318. * Return the total number of indices
  34319. * @returns the total number of indices
  34320. */
  34321. Geometry.prototype.getTotalIndices = function () {
  34322. if (!this.isReady()) {
  34323. return 0;
  34324. }
  34325. return this._indices.length;
  34326. };
  34327. /**
  34328. * Gets the index buffer array
  34329. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34330. * @returns the index buffer array
  34331. */
  34332. Geometry.prototype.getIndices = function (copyWhenShared) {
  34333. if (!this.isReady()) {
  34334. return null;
  34335. }
  34336. var orig = this._indices;
  34337. if (!copyWhenShared || this._meshes.length === 1) {
  34338. return orig;
  34339. }
  34340. else {
  34341. var len = orig.length;
  34342. var copy = [];
  34343. for (var i = 0; i < len; i++) {
  34344. copy.push(orig[i]);
  34345. }
  34346. return copy;
  34347. }
  34348. };
  34349. /**
  34350. * Gets the index buffer
  34351. * @return the index buffer
  34352. */
  34353. Geometry.prototype.getIndexBuffer = function () {
  34354. if (!this.isReady()) {
  34355. return null;
  34356. }
  34357. return this._indexBuffer;
  34358. };
  34359. /** @ignore */
  34360. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34361. if (effect === void 0) { effect = null; }
  34362. if (!effect || !this._vertexArrayObjects) {
  34363. return;
  34364. }
  34365. if (this._vertexArrayObjects[effect.key]) {
  34366. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34367. delete this._vertexArrayObjects[effect.key];
  34368. }
  34369. };
  34370. /**
  34371. * Release the associated resources for a specific mesh
  34372. * @param mesh defines the source mesh
  34373. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34374. */
  34375. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34376. var meshes = this._meshes;
  34377. var index = meshes.indexOf(mesh);
  34378. if (index === -1) {
  34379. return;
  34380. }
  34381. meshes.splice(index, 1);
  34382. mesh._geometry = null;
  34383. if (meshes.length === 0 && shouldDispose) {
  34384. this.dispose();
  34385. }
  34386. };
  34387. /**
  34388. * Apply current geometry to a given mesh
  34389. * @param mesh defines the mesh to apply geometry to
  34390. */
  34391. Geometry.prototype.applyToMesh = function (mesh) {
  34392. if (mesh._geometry === this) {
  34393. return;
  34394. }
  34395. var previousGeometry = mesh._geometry;
  34396. if (previousGeometry) {
  34397. previousGeometry.releaseForMesh(mesh);
  34398. }
  34399. var meshes = this._meshes;
  34400. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34401. mesh._geometry = this;
  34402. this._scene.pushGeometry(this);
  34403. meshes.push(mesh);
  34404. if (this.isReady()) {
  34405. this._applyToMesh(mesh);
  34406. }
  34407. else {
  34408. mesh._boundingInfo = this._boundingInfo;
  34409. }
  34410. };
  34411. Geometry.prototype.updateExtend = function (data, stride) {
  34412. if (data === void 0) { data = null; }
  34413. if (!data) {
  34414. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34415. }
  34416. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34417. };
  34418. Geometry.prototype._applyToMesh = function (mesh) {
  34419. var numOfMeshes = this._meshes.length;
  34420. // vertexBuffers
  34421. for (var kind in this._vertexBuffers) {
  34422. if (numOfMeshes === 1) {
  34423. this._vertexBuffers[kind].create();
  34424. }
  34425. var buffer = this._vertexBuffers[kind].getBuffer();
  34426. if (buffer)
  34427. buffer.references = numOfMeshes;
  34428. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34429. if (!this._extend) {
  34430. this.updateExtend(this._vertexBuffers[kind].getData());
  34431. }
  34432. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34433. mesh._createGlobalSubMesh(false);
  34434. //bounding info was just created again, world matrix should be applied again.
  34435. mesh._updateBoundingInfo();
  34436. }
  34437. }
  34438. // indexBuffer
  34439. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34440. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34441. }
  34442. if (this._indexBuffer) {
  34443. this._indexBuffer.references = numOfMeshes;
  34444. }
  34445. };
  34446. Geometry.prototype.notifyUpdate = function (kind) {
  34447. if (this.onGeometryUpdated) {
  34448. this.onGeometryUpdated(this, kind);
  34449. }
  34450. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34451. var mesh = _a[_i];
  34452. mesh._markSubMeshesAsAttributesDirty();
  34453. }
  34454. };
  34455. /**
  34456. * Load the geometry if it was flagged as delay loaded
  34457. * @param scene defines the hosting scene
  34458. * @param onLoaded defines a callback called when the geometry is loaded
  34459. */
  34460. Geometry.prototype.load = function (scene, onLoaded) {
  34461. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34462. return;
  34463. }
  34464. if (this.isReady()) {
  34465. if (onLoaded) {
  34466. onLoaded();
  34467. }
  34468. return;
  34469. }
  34470. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34471. this._queueLoad(scene, onLoaded);
  34472. };
  34473. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34474. var _this = this;
  34475. if (!this.delayLoadingFile) {
  34476. return;
  34477. }
  34478. scene._addPendingData(this);
  34479. scene._loadFile(this.delayLoadingFile, function (data) {
  34480. if (!_this._delayLoadingFunction) {
  34481. return;
  34482. }
  34483. _this._delayLoadingFunction(JSON.parse(data), _this);
  34484. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34485. _this._delayInfo = [];
  34486. scene._removePendingData(_this);
  34487. var meshes = _this._meshes;
  34488. var numOfMeshes = meshes.length;
  34489. for (var index = 0; index < numOfMeshes; index++) {
  34490. _this._applyToMesh(meshes[index]);
  34491. }
  34492. if (onLoaded) {
  34493. onLoaded();
  34494. }
  34495. }, undefined, true);
  34496. };
  34497. /**
  34498. * Invert the geometry to move from a right handed system to a left handed one.
  34499. */
  34500. Geometry.prototype.toLeftHanded = function () {
  34501. // Flip faces
  34502. var tIndices = this.getIndices(false);
  34503. if (tIndices != null && tIndices.length > 0) {
  34504. for (var i = 0; i < tIndices.length; i += 3) {
  34505. var tTemp = tIndices[i + 0];
  34506. tIndices[i + 0] = tIndices[i + 2];
  34507. tIndices[i + 2] = tTemp;
  34508. }
  34509. this.setIndices(tIndices);
  34510. }
  34511. // Negate position.z
  34512. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34513. if (tPositions != null && tPositions.length > 0) {
  34514. for (var i = 0; i < tPositions.length; i += 3) {
  34515. tPositions[i + 2] = -tPositions[i + 2];
  34516. }
  34517. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34518. }
  34519. // Negate normal.z
  34520. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34521. if (tNormals != null && tNormals.length > 0) {
  34522. for (var i = 0; i < tNormals.length; i += 3) {
  34523. tNormals[i + 2] = -tNormals[i + 2];
  34524. }
  34525. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34526. }
  34527. };
  34528. // Cache
  34529. /** @ignore */
  34530. Geometry.prototype._resetPointsArrayCache = function () {
  34531. this._positions = null;
  34532. };
  34533. /** @ignore */
  34534. Geometry.prototype._generatePointsArray = function () {
  34535. if (this._positions)
  34536. return true;
  34537. this._positions = [];
  34538. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34539. if (!data) {
  34540. return false;
  34541. }
  34542. for (var index = 0; index < data.length; index += 3) {
  34543. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34544. }
  34545. return true;
  34546. };
  34547. /**
  34548. * Gets a value indicating if the geometry is disposed
  34549. * @returns true if the geometry was disposed
  34550. */
  34551. Geometry.prototype.isDisposed = function () {
  34552. return this._isDisposed;
  34553. };
  34554. Geometry.prototype._disposeVertexArrayObjects = function () {
  34555. if (this._vertexArrayObjects) {
  34556. for (var kind in this._vertexArrayObjects) {
  34557. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34558. }
  34559. this._vertexArrayObjects = {};
  34560. }
  34561. };
  34562. /**
  34563. * Free all associated resources
  34564. */
  34565. Geometry.prototype.dispose = function () {
  34566. var meshes = this._meshes;
  34567. var numOfMeshes = meshes.length;
  34568. var index;
  34569. for (index = 0; index < numOfMeshes; index++) {
  34570. this.releaseForMesh(meshes[index]);
  34571. }
  34572. this._meshes = [];
  34573. this._disposeVertexArrayObjects();
  34574. for (var kind in this._vertexBuffers) {
  34575. this._vertexBuffers[kind].dispose();
  34576. }
  34577. this._vertexBuffers = {};
  34578. this._totalVertices = 0;
  34579. if (this._indexBuffer) {
  34580. this._engine._releaseBuffer(this._indexBuffer);
  34581. }
  34582. this._indexBuffer = null;
  34583. this._indices = [];
  34584. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34585. this.delayLoadingFile = null;
  34586. this._delayLoadingFunction = null;
  34587. this._delayInfo = [];
  34588. this._boundingInfo = null;
  34589. this._scene.removeGeometry(this);
  34590. this._isDisposed = true;
  34591. };
  34592. /**
  34593. * Clone the current geometry into a new geometry
  34594. * @param id defines the unique ID of the new geometry
  34595. * @returns a new geometry object
  34596. */
  34597. Geometry.prototype.copy = function (id) {
  34598. var vertexData = new BABYLON.VertexData();
  34599. vertexData.indices = [];
  34600. var indices = this.getIndices();
  34601. if (indices) {
  34602. for (var index = 0; index < indices.length; index++) {
  34603. vertexData.indices.push(indices[index]);
  34604. }
  34605. }
  34606. var updatable = false;
  34607. var stopChecking = false;
  34608. var kind;
  34609. for (kind in this._vertexBuffers) {
  34610. // using slice() to make a copy of the array and not just reference it
  34611. var data = this.getVerticesData(kind);
  34612. if (data instanceof Float32Array) {
  34613. vertexData.set(new Float32Array(data), kind);
  34614. }
  34615. else {
  34616. vertexData.set(data.slice(0), kind);
  34617. }
  34618. if (!stopChecking) {
  34619. var vb = this.getVertexBuffer(kind);
  34620. if (vb) {
  34621. updatable = vb.isUpdatable();
  34622. stopChecking = !updatable;
  34623. }
  34624. }
  34625. }
  34626. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34627. geometry.delayLoadState = this.delayLoadState;
  34628. geometry.delayLoadingFile = this.delayLoadingFile;
  34629. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34630. for (kind in this._delayInfo) {
  34631. geometry._delayInfo = geometry._delayInfo || [];
  34632. geometry._delayInfo.push(kind);
  34633. }
  34634. // Bounding info
  34635. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34636. return geometry;
  34637. };
  34638. /**
  34639. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34640. * @return a JSON representation of the current geometry data (without the vertices data)
  34641. */
  34642. Geometry.prototype.serialize = function () {
  34643. var serializationObject = {};
  34644. serializationObject.id = this.id;
  34645. serializationObject.updatable = this._updatable;
  34646. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34647. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34648. }
  34649. return serializationObject;
  34650. };
  34651. Geometry.prototype.toNumberArray = function (origin) {
  34652. if (Array.isArray(origin)) {
  34653. return origin;
  34654. }
  34655. else {
  34656. return Array.prototype.slice.call(origin);
  34657. }
  34658. };
  34659. /**
  34660. * Serialize all vertices data into a JSON oject
  34661. * @returns a JSON representation of the current geometry data
  34662. */
  34663. Geometry.prototype.serializeVerticeData = function () {
  34664. var serializationObject = this.serialize();
  34665. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34666. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  34667. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34668. serializationObject.positions._updatable = true;
  34669. }
  34670. }
  34671. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34672. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  34673. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34674. serializationObject.normals._updatable = true;
  34675. }
  34676. }
  34677. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34678. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  34679. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  34680. serializationObject.tangets._updatable = true;
  34681. }
  34682. }
  34683. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34684. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  34685. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  34686. serializationObject.uvs._updatable = true;
  34687. }
  34688. }
  34689. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34690. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  34691. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  34692. serializationObject.uv2s._updatable = true;
  34693. }
  34694. }
  34695. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34696. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  34697. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  34698. serializationObject.uv3s._updatable = true;
  34699. }
  34700. }
  34701. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34702. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  34703. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  34704. serializationObject.uv4s._updatable = true;
  34705. }
  34706. }
  34707. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34708. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  34709. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  34710. serializationObject.uv5s._updatable = true;
  34711. }
  34712. }
  34713. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34714. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  34715. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  34716. serializationObject.uv6s._updatable = true;
  34717. }
  34718. }
  34719. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34720. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  34721. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  34722. serializationObject.colors._updatable = true;
  34723. }
  34724. }
  34725. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34726. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  34727. serializationObject.matricesIndices._isExpanded = true;
  34728. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34729. serializationObject.matricesIndices._updatable = true;
  34730. }
  34731. }
  34732. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34733. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  34734. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34735. serializationObject.matricesWeights._updatable = true;
  34736. }
  34737. }
  34738. serializationObject.indices = this.toNumberArray(this.getIndices());
  34739. return serializationObject;
  34740. };
  34741. // Statics
  34742. /**
  34743. * Extracts a clone of a mesh geometry
  34744. * @param mesh defines the source mesh
  34745. * @param id defines the unique ID of the new geometry object
  34746. * @returns the new geometry object
  34747. */
  34748. Geometry.ExtractFromMesh = function (mesh, id) {
  34749. var geometry = mesh._geometry;
  34750. if (!geometry) {
  34751. return null;
  34752. }
  34753. return geometry.copy(id);
  34754. };
  34755. /**
  34756. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34757. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34758. * Be aware Math.random() could cause collisions, but:
  34759. * "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"
  34760. * @returns a string containing a new GUID
  34761. */
  34762. Geometry.RandomId = function () {
  34763. return BABYLON.Tools.RandomId();
  34764. };
  34765. /** @ignore */
  34766. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  34767. var scene = mesh.getScene();
  34768. // Geometry
  34769. var geometryId = parsedGeometry.geometryId;
  34770. if (geometryId) {
  34771. var geometry = scene.getGeometryByID(geometryId);
  34772. if (geometry) {
  34773. geometry.applyToMesh(mesh);
  34774. }
  34775. }
  34776. else if (parsedGeometry instanceof ArrayBuffer) {
  34777. var binaryInfo = mesh._binaryInfo;
  34778. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34779. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34780. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34781. }
  34782. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34783. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34784. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34785. }
  34786. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  34787. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  34788. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  34789. }
  34790. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34791. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34792. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34793. }
  34794. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34795. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34796. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34797. }
  34798. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34799. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34800. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34801. }
  34802. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34803. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34804. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34805. }
  34806. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34807. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34808. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34809. }
  34810. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34811. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34812. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34813. }
  34814. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34815. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34816. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34817. }
  34818. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34819. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34820. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34821. }
  34822. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34823. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34824. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34825. }
  34826. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34827. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34828. mesh.setIndices(indicesData, null);
  34829. }
  34830. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34831. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34832. mesh.subMeshes = [];
  34833. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34834. var materialIndex = subMeshesData[(i * 5) + 0];
  34835. var verticesStart = subMeshesData[(i * 5) + 1];
  34836. var verticesCount = subMeshesData[(i * 5) + 2];
  34837. var indexStart = subMeshesData[(i * 5) + 3];
  34838. var indexCount = subMeshesData[(i * 5) + 4];
  34839. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34840. }
  34841. }
  34842. }
  34843. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34844. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  34845. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  34846. if (parsedGeometry.tangents) {
  34847. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  34848. }
  34849. if (parsedGeometry.uvs) {
  34850. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  34851. }
  34852. if (parsedGeometry.uvs2) {
  34853. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  34854. }
  34855. if (parsedGeometry.uvs3) {
  34856. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  34857. }
  34858. if (parsedGeometry.uvs4) {
  34859. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  34860. }
  34861. if (parsedGeometry.uvs5) {
  34862. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  34863. }
  34864. if (parsedGeometry.uvs6) {
  34865. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  34866. }
  34867. if (parsedGeometry.colors) {
  34868. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  34869. }
  34870. if (parsedGeometry.matricesIndices) {
  34871. if (!parsedGeometry.matricesIndices._isExpanded) {
  34872. var floatIndices = [];
  34873. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34874. var matricesIndex = parsedGeometry.matricesIndices[i];
  34875. floatIndices.push(matricesIndex & 0x000000FF);
  34876. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34877. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34878. floatIndices.push(matricesIndex >> 24);
  34879. }
  34880. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  34881. }
  34882. else {
  34883. delete parsedGeometry.matricesIndices._isExpanded;
  34884. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  34885. }
  34886. }
  34887. if (parsedGeometry.matricesIndicesExtra) {
  34888. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34889. var floatIndices = [];
  34890. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34891. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34892. floatIndices.push(matricesIndex & 0x000000FF);
  34893. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34894. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34895. floatIndices.push(matricesIndex >> 24);
  34896. }
  34897. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  34898. }
  34899. else {
  34900. delete parsedGeometry.matricesIndices._isExpanded;
  34901. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  34902. }
  34903. }
  34904. if (parsedGeometry.matricesWeights) {
  34905. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  34906. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  34907. }
  34908. if (parsedGeometry.matricesWeightsExtra) {
  34909. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  34910. }
  34911. mesh.setIndices(parsedGeometry.indices, null);
  34912. }
  34913. // SubMeshes
  34914. if (parsedGeometry.subMeshes) {
  34915. mesh.subMeshes = [];
  34916. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  34917. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  34918. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  34919. }
  34920. }
  34921. // Flat shading
  34922. if (mesh._shouldGenerateFlatShading) {
  34923. mesh.convertToFlatShadedMesh();
  34924. delete mesh._shouldGenerateFlatShading;
  34925. }
  34926. // Update
  34927. mesh.computeWorldMatrix(true);
  34928. // Octree
  34929. var sceneOctree = scene.selectionOctree;
  34930. if (sceneOctree !== undefined && sceneOctree !== null) {
  34931. sceneOctree.addMesh(mesh);
  34932. }
  34933. };
  34934. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  34935. var epsilon = 1e-3;
  34936. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  34937. return;
  34938. }
  34939. var noInfluenceBoneIndex = 0.0;
  34940. if (parsedGeometry.skeletonId > -1) {
  34941. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  34942. if (!skeleton) {
  34943. return;
  34944. }
  34945. noInfluenceBoneIndex = skeleton.bones.length;
  34946. }
  34947. else {
  34948. return;
  34949. }
  34950. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34951. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34952. var matricesWeights = parsedGeometry.matricesWeights;
  34953. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  34954. var influencers = parsedGeometry.numBoneInfluencer;
  34955. var size = matricesWeights.length;
  34956. for (var i = 0; i < size; i += 4) {
  34957. var weight = 0.0;
  34958. var firstZeroWeight = -1;
  34959. for (var j = 0; j < 4; j++) {
  34960. var w = matricesWeights[i + j];
  34961. weight += w;
  34962. if (w < epsilon && firstZeroWeight < 0) {
  34963. firstZeroWeight = j;
  34964. }
  34965. }
  34966. if (matricesWeightsExtra) {
  34967. for (var j = 0; j < 4; j++) {
  34968. var w = matricesWeightsExtra[i + j];
  34969. weight += w;
  34970. if (w < epsilon && firstZeroWeight < 0) {
  34971. firstZeroWeight = j + 4;
  34972. }
  34973. }
  34974. }
  34975. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  34976. firstZeroWeight = influencers - 1;
  34977. }
  34978. if (weight > epsilon) {
  34979. var mweight = 1.0 / weight;
  34980. for (var j = 0; j < 4; j++) {
  34981. matricesWeights[i + j] *= mweight;
  34982. }
  34983. if (matricesWeightsExtra) {
  34984. for (var j = 0; j < 4; j++) {
  34985. matricesWeightsExtra[i + j] *= mweight;
  34986. }
  34987. }
  34988. }
  34989. else {
  34990. if (firstZeroWeight >= 4) {
  34991. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  34992. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  34993. }
  34994. else {
  34995. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  34996. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  34997. }
  34998. }
  34999. }
  35000. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35001. if (parsedGeometry.matricesWeightsExtra) {
  35002. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35003. }
  35004. };
  35005. /**
  35006. * Create a new geometry from persisted data (Using .babylon file format)
  35007. * @param parsedVertexData defines the persisted data
  35008. * @param scene defines the hosting scene
  35009. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35010. * @returns the new geometry object
  35011. */
  35012. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35013. if (scene.getGeometryByID(parsedVertexData.id)) {
  35014. return null; // null since geometry could be something else than a box...
  35015. }
  35016. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35017. if (BABYLON.Tags) {
  35018. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35019. }
  35020. if (parsedVertexData.delayLoadingFile) {
  35021. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35022. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35023. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35024. geometry._delayInfo = [];
  35025. if (parsedVertexData.hasUVs) {
  35026. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35027. }
  35028. if (parsedVertexData.hasUVs2) {
  35029. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35030. }
  35031. if (parsedVertexData.hasUVs3) {
  35032. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35033. }
  35034. if (parsedVertexData.hasUVs4) {
  35035. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35036. }
  35037. if (parsedVertexData.hasUVs5) {
  35038. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35039. }
  35040. if (parsedVertexData.hasUVs6) {
  35041. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35042. }
  35043. if (parsedVertexData.hasColors) {
  35044. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35045. }
  35046. if (parsedVertexData.hasMatricesIndices) {
  35047. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35048. }
  35049. if (parsedVertexData.hasMatricesWeights) {
  35050. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35051. }
  35052. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35053. }
  35054. else {
  35055. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35056. }
  35057. scene.pushGeometry(geometry, true);
  35058. return geometry;
  35059. };
  35060. return Geometry;
  35061. }());
  35062. BABYLON.Geometry = Geometry;
  35063. // Primitives
  35064. /// Abstract class
  35065. /**
  35066. * Abstract class used to provide common services for all typed geometries
  35067. */
  35068. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35069. __extends(_PrimitiveGeometry, _super);
  35070. /**
  35071. * Creates a new typed geometry
  35072. * @param id defines the unique ID of the geometry
  35073. * @param scene defines the hosting scene
  35074. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35075. * @param mesh defines the hosting mesh (can be null)
  35076. */
  35077. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35078. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35079. if (mesh === void 0) { mesh = null; }
  35080. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35081. _this._canBeRegenerated = _canBeRegenerated;
  35082. _this._beingRegenerated = true;
  35083. _this.regenerate();
  35084. _this._beingRegenerated = false;
  35085. return _this;
  35086. }
  35087. /**
  35088. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35089. * @returns true if the geometry can be regenerated
  35090. */
  35091. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35092. return this._canBeRegenerated;
  35093. };
  35094. /**
  35095. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35096. */
  35097. _PrimitiveGeometry.prototype.regenerate = function () {
  35098. if (!this._canBeRegenerated) {
  35099. return;
  35100. }
  35101. this._beingRegenerated = true;
  35102. this.setAllVerticesData(this._regenerateVertexData(), false);
  35103. this._beingRegenerated = false;
  35104. };
  35105. /**
  35106. * Clone the geometry
  35107. * @param id defines the unique ID of the new geometry
  35108. * @returns the new geometry
  35109. */
  35110. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35111. return _super.prototype.copy.call(this, id);
  35112. };
  35113. // overrides
  35114. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35115. if (!this._beingRegenerated) {
  35116. return;
  35117. }
  35118. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35119. };
  35120. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35121. if (!this._beingRegenerated) {
  35122. return;
  35123. }
  35124. _super.prototype.setVerticesData.call(this, kind, data, false);
  35125. };
  35126. // to override
  35127. /** @ignore */
  35128. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35129. throw new Error("Abstract method");
  35130. };
  35131. _PrimitiveGeometry.prototype.copy = function (id) {
  35132. throw new Error("Must be overriden in sub-classes.");
  35133. };
  35134. _PrimitiveGeometry.prototype.serialize = function () {
  35135. var serializationObject = _super.prototype.serialize.call(this);
  35136. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35137. return serializationObject;
  35138. };
  35139. return _PrimitiveGeometry;
  35140. }(Geometry));
  35141. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35142. /**
  35143. * Creates a ribbon geometry
  35144. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35145. */
  35146. var RibbonGeometry = /** @class */ (function (_super) {
  35147. __extends(RibbonGeometry, _super);
  35148. /**
  35149. * Creates a ribbon geometry
  35150. * @param id defines the unique ID of the geometry
  35151. * @param scene defines the hosting scene
  35152. * @param pathArray defines the array of paths to use
  35153. * @param closeArray defines if the last path and the first path must be joined
  35154. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35155. * @param offset defines the offset between points
  35156. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35157. * @param mesh defines the hosting mesh (can be null)
  35158. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35159. */
  35160. function RibbonGeometry(id, scene,
  35161. /**
  35162. * Defines the array of paths to use
  35163. */
  35164. pathArray,
  35165. /**
  35166. * Defines if the last and first points of each path in your pathArray must be joined
  35167. */
  35168. closeArray,
  35169. /**
  35170. * Defines if the last and first points of each path in your pathArray must be joined
  35171. */
  35172. closePath,
  35173. /**
  35174. * Defines the offset between points
  35175. */
  35176. offset, canBeRegenerated, mesh,
  35177. /**
  35178. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35179. */
  35180. side) {
  35181. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35182. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35183. _this.pathArray = pathArray;
  35184. _this.closeArray = closeArray;
  35185. _this.closePath = closePath;
  35186. _this.offset = offset;
  35187. _this.side = side;
  35188. return _this;
  35189. }
  35190. /** @ignore */
  35191. RibbonGeometry.prototype._regenerateVertexData = function () {
  35192. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35193. };
  35194. RibbonGeometry.prototype.copy = function (id) {
  35195. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35196. };
  35197. return RibbonGeometry;
  35198. }(_PrimitiveGeometry));
  35199. BABYLON.RibbonGeometry = RibbonGeometry;
  35200. /**
  35201. * Creates a box geometry
  35202. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35203. */
  35204. var BoxGeometry = /** @class */ (function (_super) {
  35205. __extends(BoxGeometry, _super);
  35206. /**
  35207. * Creates a box geometry
  35208. * @param id defines the unique ID of the geometry
  35209. * @param scene defines the hosting scene
  35210. * @param size defines the zise of the box (width, height and depth are the same)
  35211. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35212. * @param mesh defines the hosting mesh (can be null)
  35213. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35214. */
  35215. function BoxGeometry(id, scene,
  35216. /**
  35217. * Defines the zise of the box (width, height and depth are the same)
  35218. */
  35219. size, canBeRegenerated, mesh,
  35220. /**
  35221. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35222. */
  35223. side) {
  35224. if (mesh === void 0) { mesh = null; }
  35225. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35226. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35227. _this.size = size;
  35228. _this.side = side;
  35229. return _this;
  35230. }
  35231. BoxGeometry.prototype._regenerateVertexData = function () {
  35232. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35233. };
  35234. BoxGeometry.prototype.copy = function (id) {
  35235. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35236. };
  35237. BoxGeometry.prototype.serialize = function () {
  35238. var serializationObject = _super.prototype.serialize.call(this);
  35239. serializationObject.size = this.size;
  35240. return serializationObject;
  35241. };
  35242. BoxGeometry.Parse = function (parsedBox, scene) {
  35243. if (scene.getGeometryByID(parsedBox.id)) {
  35244. return null; // null since geometry could be something else than a box...
  35245. }
  35246. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35247. if (BABYLON.Tags) {
  35248. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35249. }
  35250. scene.pushGeometry(box, true);
  35251. return box;
  35252. };
  35253. return BoxGeometry;
  35254. }(_PrimitiveGeometry));
  35255. BABYLON.BoxGeometry = BoxGeometry;
  35256. /**
  35257. * Creates a sphere geometry
  35258. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35259. */
  35260. var SphereGeometry = /** @class */ (function (_super) {
  35261. __extends(SphereGeometry, _super);
  35262. /**
  35263. * Create a new sphere geometry
  35264. * @param id defines the unique ID of the geometry
  35265. * @param scene defines the hosting scene
  35266. * @param segments defines the number of segments to use to create the sphere
  35267. * @param diameter defines the diameter of the sphere
  35268. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35269. * @param mesh defines the hosting mesh (can be null)
  35270. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35271. */
  35272. function SphereGeometry(id, scene,
  35273. /**
  35274. * Defines the number of segments to use to create the sphere
  35275. */
  35276. segments,
  35277. /**
  35278. * Defines the diameter of the sphere
  35279. */
  35280. diameter, canBeRegenerated, mesh,
  35281. /**
  35282. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35283. */
  35284. side) {
  35285. if (mesh === void 0) { mesh = null; }
  35286. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35287. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35288. _this.segments = segments;
  35289. _this.diameter = diameter;
  35290. _this.side = side;
  35291. return _this;
  35292. }
  35293. SphereGeometry.prototype._regenerateVertexData = function () {
  35294. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35295. };
  35296. SphereGeometry.prototype.copy = function (id) {
  35297. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35298. };
  35299. SphereGeometry.prototype.serialize = function () {
  35300. var serializationObject = _super.prototype.serialize.call(this);
  35301. serializationObject.segments = this.segments;
  35302. serializationObject.diameter = this.diameter;
  35303. return serializationObject;
  35304. };
  35305. SphereGeometry.Parse = function (parsedSphere, scene) {
  35306. if (scene.getGeometryByID(parsedSphere.id)) {
  35307. return null; // null since geometry could be something else than a sphere...
  35308. }
  35309. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35310. if (BABYLON.Tags) {
  35311. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35312. }
  35313. scene.pushGeometry(sphere, true);
  35314. return sphere;
  35315. };
  35316. return SphereGeometry;
  35317. }(_PrimitiveGeometry));
  35318. BABYLON.SphereGeometry = SphereGeometry;
  35319. /**
  35320. * Creates a disc geometry
  35321. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35322. */
  35323. var DiscGeometry = /** @class */ (function (_super) {
  35324. __extends(DiscGeometry, _super);
  35325. /**
  35326. * Creates a new disc geometry
  35327. * @param id defines the unique ID of the geometry
  35328. * @param scene defines the hosting scene
  35329. * @param radius defines the radius of the disc
  35330. * @param tessellation defines the tesselation factor to apply to the disc
  35331. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35332. * @param mesh defines the hosting mesh (can be null)
  35333. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35334. */
  35335. function DiscGeometry(id, scene,
  35336. /**
  35337. * Defines the radius of the disc
  35338. */
  35339. radius,
  35340. /**
  35341. * Defines the tesselation factor to apply to the disc
  35342. */
  35343. tessellation, canBeRegenerated, mesh,
  35344. /**
  35345. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35346. */
  35347. side) {
  35348. if (mesh === void 0) { mesh = null; }
  35349. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35350. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35351. _this.radius = radius;
  35352. _this.tessellation = tessellation;
  35353. _this.side = side;
  35354. return _this;
  35355. }
  35356. DiscGeometry.prototype._regenerateVertexData = function () {
  35357. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35358. };
  35359. DiscGeometry.prototype.copy = function (id) {
  35360. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35361. };
  35362. return DiscGeometry;
  35363. }(_PrimitiveGeometry));
  35364. BABYLON.DiscGeometry = DiscGeometry;
  35365. /**
  35366. * Creates a new cylinder geometry
  35367. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35368. */
  35369. var CylinderGeometry = /** @class */ (function (_super) {
  35370. __extends(CylinderGeometry, _super);
  35371. /**
  35372. * Creates a new cylinder geometry
  35373. * @param id defines the unique ID of the geometry
  35374. * @param scene defines the hosting scene
  35375. * @param height defines the height of the cylinder
  35376. * @param diameterTop defines the diameter of the cylinder's top cap
  35377. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35378. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35379. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35380. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35381. * @param mesh defines the hosting mesh (can be null)
  35382. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35383. */
  35384. function CylinderGeometry(id, scene,
  35385. /**
  35386. * Defines the height of the cylinder
  35387. */
  35388. height,
  35389. /**
  35390. * Defines the diameter of the cylinder's top cap
  35391. */
  35392. diameterTop,
  35393. /**
  35394. * Defines the diameter of the cylinder's bottom cap
  35395. */
  35396. diameterBottom,
  35397. /**
  35398. * Defines the tessellation factor to apply to the cylinder
  35399. */
  35400. tessellation,
  35401. /**
  35402. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35403. */
  35404. subdivisions, canBeRegenerated, mesh,
  35405. /**
  35406. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35407. */
  35408. side) {
  35409. if (subdivisions === void 0) { subdivisions = 1; }
  35410. if (mesh === void 0) { mesh = null; }
  35411. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35412. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35413. _this.height = height;
  35414. _this.diameterTop = diameterTop;
  35415. _this.diameterBottom = diameterBottom;
  35416. _this.tessellation = tessellation;
  35417. _this.subdivisions = subdivisions;
  35418. _this.side = side;
  35419. return _this;
  35420. }
  35421. CylinderGeometry.prototype._regenerateVertexData = function () {
  35422. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35423. };
  35424. CylinderGeometry.prototype.copy = function (id) {
  35425. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35426. };
  35427. CylinderGeometry.prototype.serialize = function () {
  35428. var serializationObject = _super.prototype.serialize.call(this);
  35429. serializationObject.height = this.height;
  35430. serializationObject.diameterTop = this.diameterTop;
  35431. serializationObject.diameterBottom = this.diameterBottom;
  35432. serializationObject.tessellation = this.tessellation;
  35433. return serializationObject;
  35434. };
  35435. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35436. if (scene.getGeometryByID(parsedCylinder.id)) {
  35437. return null; // null since geometry could be something else than a cylinder...
  35438. }
  35439. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35440. if (BABYLON.Tags) {
  35441. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35442. }
  35443. scene.pushGeometry(cylinder, true);
  35444. return cylinder;
  35445. };
  35446. return CylinderGeometry;
  35447. }(_PrimitiveGeometry));
  35448. BABYLON.CylinderGeometry = CylinderGeometry;
  35449. /**
  35450. * Creates a new torus geometry
  35451. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35452. */
  35453. var TorusGeometry = /** @class */ (function (_super) {
  35454. __extends(TorusGeometry, _super);
  35455. /**
  35456. * Creates a new torus geometry
  35457. * @param id defines the unique ID of the geometry
  35458. * @param scene defines the hosting scene
  35459. * @param diameter defines the diameter of the torus
  35460. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35461. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35462. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35463. * @param mesh defines the hosting mesh (can be null)
  35464. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35465. */
  35466. function TorusGeometry(id, scene,
  35467. /**
  35468. * Defines the diameter of the torus
  35469. */
  35470. diameter,
  35471. /**
  35472. * Defines the thickness of the torus (ie. internal diameter)
  35473. */
  35474. thickness,
  35475. /**
  35476. * Defines the tesselation factor to apply to the torus
  35477. */
  35478. tessellation, canBeRegenerated, mesh,
  35479. /**
  35480. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35481. */
  35482. side) {
  35483. if (mesh === void 0) { mesh = null; }
  35484. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35485. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35486. _this.diameter = diameter;
  35487. _this.thickness = thickness;
  35488. _this.tessellation = tessellation;
  35489. _this.side = side;
  35490. return _this;
  35491. }
  35492. TorusGeometry.prototype._regenerateVertexData = function () {
  35493. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35494. };
  35495. TorusGeometry.prototype.copy = function (id) {
  35496. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35497. };
  35498. TorusGeometry.prototype.serialize = function () {
  35499. var serializationObject = _super.prototype.serialize.call(this);
  35500. serializationObject.diameter = this.diameter;
  35501. serializationObject.thickness = this.thickness;
  35502. serializationObject.tessellation = this.tessellation;
  35503. return serializationObject;
  35504. };
  35505. TorusGeometry.Parse = function (parsedTorus, scene) {
  35506. if (scene.getGeometryByID(parsedTorus.id)) {
  35507. return null; // null since geometry could be something else than a torus...
  35508. }
  35509. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35510. if (BABYLON.Tags) {
  35511. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35512. }
  35513. scene.pushGeometry(torus, true);
  35514. return torus;
  35515. };
  35516. return TorusGeometry;
  35517. }(_PrimitiveGeometry));
  35518. BABYLON.TorusGeometry = TorusGeometry;
  35519. /**
  35520. * Creates a new ground geometry
  35521. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35522. */
  35523. var GroundGeometry = /** @class */ (function (_super) {
  35524. __extends(GroundGeometry, _super);
  35525. /**
  35526. * Creates a new ground geometry
  35527. * @param id defines the unique ID of the geometry
  35528. * @param scene defines the hosting scene
  35529. * @param width defines the width of the ground
  35530. * @param height defines the height of the ground
  35531. * @param subdivisions defines the subdivisions to apply to the ground
  35532. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35533. * @param mesh defines the hosting mesh (can be null)
  35534. */
  35535. function GroundGeometry(id, scene,
  35536. /**
  35537. * Defines the width of the ground
  35538. */
  35539. width,
  35540. /**
  35541. * Defines the height of the ground
  35542. */
  35543. height,
  35544. /**
  35545. * Defines the subdivisions to apply to the ground
  35546. */
  35547. subdivisions, canBeRegenerated, mesh) {
  35548. if (mesh === void 0) { mesh = null; }
  35549. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35550. _this.width = width;
  35551. _this.height = height;
  35552. _this.subdivisions = subdivisions;
  35553. return _this;
  35554. }
  35555. GroundGeometry.prototype._regenerateVertexData = function () {
  35556. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35557. };
  35558. GroundGeometry.prototype.copy = function (id) {
  35559. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35560. };
  35561. GroundGeometry.prototype.serialize = function () {
  35562. var serializationObject = _super.prototype.serialize.call(this);
  35563. serializationObject.width = this.width;
  35564. serializationObject.height = this.height;
  35565. serializationObject.subdivisions = this.subdivisions;
  35566. return serializationObject;
  35567. };
  35568. GroundGeometry.Parse = function (parsedGround, scene) {
  35569. if (scene.getGeometryByID(parsedGround.id)) {
  35570. return null; // null since geometry could be something else than a ground...
  35571. }
  35572. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35573. if (BABYLON.Tags) {
  35574. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35575. }
  35576. scene.pushGeometry(ground, true);
  35577. return ground;
  35578. };
  35579. return GroundGeometry;
  35580. }(_PrimitiveGeometry));
  35581. BABYLON.GroundGeometry = GroundGeometry;
  35582. /**
  35583. * Creates a tiled ground geometry
  35584. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35585. */
  35586. var TiledGroundGeometry = /** @class */ (function (_super) {
  35587. __extends(TiledGroundGeometry, _super);
  35588. /**
  35589. * Creates a tiled ground geometry
  35590. * @param id defines the unique ID of the geometry
  35591. * @param scene defines the hosting scene
  35592. * @param xmin defines the minimum value on X axis
  35593. * @param zmin defines the minimum value on Z axis
  35594. * @param xmax defines the maximum value on X axis
  35595. * @param zmax defines the maximum value on Z axis
  35596. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35597. * @param precision defines the precision to use when computing the tiles
  35598. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35599. * @param mesh defines the hosting mesh (can be null)
  35600. */
  35601. function TiledGroundGeometry(id, scene,
  35602. /**
  35603. * Defines the minimum value on X axis
  35604. */
  35605. xmin,
  35606. /**
  35607. * Defines the minimum value on Z axis
  35608. */
  35609. zmin,
  35610. /**
  35611. * Defines the maximum value on X axis
  35612. */
  35613. xmax,
  35614. /**
  35615. * Defines the maximum value on Z axis
  35616. */
  35617. zmax,
  35618. /**
  35619. * Defines the subdivisions to apply to the ground
  35620. */
  35621. subdivisions,
  35622. /**
  35623. * Defines the precision to use when computing the tiles
  35624. */
  35625. precision, canBeRegenerated, mesh) {
  35626. if (mesh === void 0) { mesh = null; }
  35627. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35628. _this.xmin = xmin;
  35629. _this.zmin = zmin;
  35630. _this.xmax = xmax;
  35631. _this.zmax = zmax;
  35632. _this.subdivisions = subdivisions;
  35633. _this.precision = precision;
  35634. return _this;
  35635. }
  35636. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35637. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35638. };
  35639. TiledGroundGeometry.prototype.copy = function (id) {
  35640. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35641. };
  35642. return TiledGroundGeometry;
  35643. }(_PrimitiveGeometry));
  35644. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35645. /**
  35646. * Creates a plane geometry
  35647. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  35648. */
  35649. var PlaneGeometry = /** @class */ (function (_super) {
  35650. __extends(PlaneGeometry, _super);
  35651. /**
  35652. * Creates a plane geometry
  35653. * @param id defines the unique ID of the geometry
  35654. * @param scene defines the hosting scene
  35655. * @param size defines the size of the plane (width === height)
  35656. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35657. * @param mesh defines the hosting mesh (can be null)
  35658. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35659. */
  35660. function PlaneGeometry(id, scene,
  35661. /**
  35662. * Defines the size of the plane (width === height)
  35663. */
  35664. size, canBeRegenerated, mesh,
  35665. /**
  35666. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35667. */
  35668. side) {
  35669. if (mesh === void 0) { mesh = null; }
  35670. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35671. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35672. _this.size = size;
  35673. _this.side = side;
  35674. return _this;
  35675. }
  35676. PlaneGeometry.prototype._regenerateVertexData = function () {
  35677. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35678. };
  35679. PlaneGeometry.prototype.copy = function (id) {
  35680. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35681. };
  35682. PlaneGeometry.prototype.serialize = function () {
  35683. var serializationObject = _super.prototype.serialize.call(this);
  35684. serializationObject.size = this.size;
  35685. return serializationObject;
  35686. };
  35687. PlaneGeometry.Parse = function (parsedPlane, scene) {
  35688. if (scene.getGeometryByID(parsedPlane.id)) {
  35689. return null; // null since geometry could be something else than a ground...
  35690. }
  35691. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35692. if (BABYLON.Tags) {
  35693. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35694. }
  35695. scene.pushGeometry(plane, true);
  35696. return plane;
  35697. };
  35698. return PlaneGeometry;
  35699. }(_PrimitiveGeometry));
  35700. BABYLON.PlaneGeometry = PlaneGeometry;
  35701. /**
  35702. * Creates a torus knot geometry
  35703. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  35704. */
  35705. var TorusKnotGeometry = /** @class */ (function (_super) {
  35706. __extends(TorusKnotGeometry, _super);
  35707. /**
  35708. * Creates a torus knot geometry
  35709. * @param id defines the unique ID of the geometry
  35710. * @param scene defines the hosting scene
  35711. * @param radius defines the radius of the torus knot
  35712. * @param tube defines the thickness of the torus knot tube
  35713. * @param radialSegments defines the number of radial segments
  35714. * @param tubularSegments defines the number of tubular segments
  35715. * @param p defines the first number of windings
  35716. * @param q defines the second number of windings
  35717. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35718. * @param mesh defines the hosting mesh (can be null)
  35719. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35720. */
  35721. function TorusKnotGeometry(id, scene,
  35722. /**
  35723. * Defines the radius of the torus knot
  35724. */
  35725. radius,
  35726. /**
  35727. * Defines the thickness of the torus knot tube
  35728. */
  35729. tube,
  35730. /**
  35731. * Defines the number of radial segments
  35732. */
  35733. radialSegments,
  35734. /**
  35735. * Defines the number of tubular segments
  35736. */
  35737. tubularSegments,
  35738. /**
  35739. * Defines the first number of windings
  35740. */
  35741. p,
  35742. /**
  35743. * Defines the second number of windings
  35744. */
  35745. q, canBeRegenerated, mesh,
  35746. /**
  35747. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35748. */
  35749. side) {
  35750. if (mesh === void 0) { mesh = null; }
  35751. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35752. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35753. _this.radius = radius;
  35754. _this.tube = tube;
  35755. _this.radialSegments = radialSegments;
  35756. _this.tubularSegments = tubularSegments;
  35757. _this.p = p;
  35758. _this.q = q;
  35759. _this.side = side;
  35760. return _this;
  35761. }
  35762. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  35763. 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 });
  35764. };
  35765. TorusKnotGeometry.prototype.copy = function (id) {
  35766. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35767. };
  35768. TorusKnotGeometry.prototype.serialize = function () {
  35769. var serializationObject = _super.prototype.serialize.call(this);
  35770. serializationObject.radius = this.radius;
  35771. serializationObject.tube = this.tube;
  35772. serializationObject.radialSegments = this.radialSegments;
  35773. serializationObject.tubularSegments = this.tubularSegments;
  35774. serializationObject.p = this.p;
  35775. serializationObject.q = this.q;
  35776. return serializationObject;
  35777. };
  35778. ;
  35779. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  35780. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35781. return null; // null since geometry could be something else than a ground...
  35782. }
  35783. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35784. if (BABYLON.Tags) {
  35785. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35786. }
  35787. scene.pushGeometry(torusKnot, true);
  35788. return torusKnot;
  35789. };
  35790. return TorusKnotGeometry;
  35791. }(_PrimitiveGeometry));
  35792. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  35793. //}
  35794. })(BABYLON || (BABYLON = {}));
  35795. //# sourceMappingURL=babylon.geometry.js.map
  35796. var BABYLON;
  35797. (function (BABYLON) {
  35798. /**
  35799. * PostProcessManager is used to manage one or more post processes or post process pipelines
  35800. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  35801. */
  35802. var PostProcessManager = /** @class */ (function () {
  35803. /**
  35804. * Creates a new instance of @see PostProcess
  35805. * @param scene The scene that the post process is associated with.
  35806. */
  35807. function PostProcessManager(scene) {
  35808. this._vertexBuffers = {};
  35809. this._scene = scene;
  35810. }
  35811. PostProcessManager.prototype._prepareBuffers = function () {
  35812. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35813. return;
  35814. }
  35815. // VBO
  35816. var vertices = [];
  35817. vertices.push(1, 1);
  35818. vertices.push(-1, 1);
  35819. vertices.push(-1, -1);
  35820. vertices.push(1, -1);
  35821. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  35822. this._buildIndexBuffer();
  35823. };
  35824. PostProcessManager.prototype._buildIndexBuffer = function () {
  35825. // Indices
  35826. var indices = [];
  35827. indices.push(0);
  35828. indices.push(1);
  35829. indices.push(2);
  35830. indices.push(0);
  35831. indices.push(2);
  35832. indices.push(3);
  35833. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  35834. };
  35835. /**
  35836. * Rebuilds the vertex buffers of the manager.
  35837. */
  35838. PostProcessManager.prototype._rebuild = function () {
  35839. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35840. if (!vb) {
  35841. return;
  35842. }
  35843. vb._rebuild();
  35844. this._buildIndexBuffer();
  35845. };
  35846. // Methods
  35847. /**
  35848. * Prepares a frame to be run through a post process.
  35849. * @param sourceTexture The input texture to the post procesess. (default: null)
  35850. * @param postProcesses An array of post processes to be run. (default: null)
  35851. * @returns True if the post processes were able to be run.
  35852. */
  35853. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  35854. if (sourceTexture === void 0) { sourceTexture = null; }
  35855. if (postProcesses === void 0) { postProcesses = null; }
  35856. var camera = this._scene.activeCamera;
  35857. if (!camera) {
  35858. return false;
  35859. }
  35860. var postProcesses = postProcesses || camera._postProcesses;
  35861. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35862. return false;
  35863. }
  35864. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  35865. return true;
  35866. };
  35867. /**
  35868. * Manually render a set of post processes to a texture.
  35869. * @param postProcesses An array of post processes to be run.
  35870. * @param targetTexture The target texture to render to.
  35871. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  35872. */
  35873. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  35874. if (targetTexture === void 0) { targetTexture = null; }
  35875. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  35876. var engine = this._scene.getEngine();
  35877. for (var index = 0; index < postProcesses.length; index++) {
  35878. if (index < postProcesses.length - 1) {
  35879. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35880. }
  35881. else {
  35882. if (targetTexture) {
  35883. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  35884. }
  35885. else {
  35886. engine.restoreDefaultFramebuffer();
  35887. }
  35888. }
  35889. var pp = postProcesses[index];
  35890. var effect = pp.apply();
  35891. if (effect) {
  35892. pp.onBeforeRenderObservable.notifyObservers(effect);
  35893. // VBOs
  35894. this._prepareBuffers();
  35895. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35896. // Draw order
  35897. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  35898. pp.onAfterRenderObservable.notifyObservers(effect);
  35899. }
  35900. }
  35901. // Restore depth buffer
  35902. engine.setDepthBuffer(true);
  35903. engine.setDepthWrite(true);
  35904. };
  35905. /**
  35906. * Finalize the result of the output of the postprocesses.
  35907. * @param doNotPresent If true the result will not be displayed to the screen.
  35908. * @param targetTexture The target texture to render to.
  35909. * @param faceIndex The index of the face to bind the target texture to.
  35910. * @param postProcesses The array of post processes to render.
  35911. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  35912. */
  35913. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  35914. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  35915. var camera = this._scene.activeCamera;
  35916. if (!camera) {
  35917. return;
  35918. }
  35919. postProcesses = postProcesses || camera._postProcesses;
  35920. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35921. return;
  35922. }
  35923. var engine = this._scene.getEngine();
  35924. for (var index = 0, len = postProcesses.length; index < len; index++) {
  35925. if (index < len - 1) {
  35926. postProcesses[index + 1].activate(camera, targetTexture);
  35927. }
  35928. else {
  35929. if (targetTexture) {
  35930. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  35931. }
  35932. else {
  35933. engine.restoreDefaultFramebuffer();
  35934. }
  35935. }
  35936. if (doNotPresent) {
  35937. break;
  35938. }
  35939. var pp = postProcesses[index];
  35940. var effect = pp.apply();
  35941. if (effect) {
  35942. pp.onBeforeRenderObservable.notifyObservers(effect);
  35943. // VBOs
  35944. this._prepareBuffers();
  35945. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35946. // Draw order
  35947. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  35948. pp.onAfterRenderObservable.notifyObservers(effect);
  35949. }
  35950. }
  35951. // Restore states
  35952. engine.setDepthBuffer(true);
  35953. engine.setDepthWrite(true);
  35954. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35955. };
  35956. /**
  35957. * Disposes of the post process manager.
  35958. */
  35959. PostProcessManager.prototype.dispose = function () {
  35960. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35961. if (buffer) {
  35962. buffer.dispose();
  35963. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  35964. }
  35965. if (this._indexBuffer) {
  35966. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35967. this._indexBuffer = null;
  35968. }
  35969. };
  35970. return PostProcessManager;
  35971. }());
  35972. BABYLON.PostProcessManager = PostProcessManager;
  35973. })(BABYLON || (BABYLON = {}));
  35974. //# sourceMappingURL=babylon.postProcessManager.js.map
  35975. var BABYLON;
  35976. (function (BABYLON) {
  35977. /**
  35978. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  35979. */
  35980. var PerformanceMonitor = /** @class */ (function () {
  35981. /**
  35982. * constructor
  35983. * @param frameSampleSize The number of samples required to saturate the sliding window
  35984. */
  35985. function PerformanceMonitor(frameSampleSize) {
  35986. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  35987. this._enabled = true;
  35988. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  35989. }
  35990. /**
  35991. * Samples current frame
  35992. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  35993. */
  35994. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  35995. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  35996. if (!this._enabled)
  35997. return;
  35998. if (this._lastFrameTimeMs != null) {
  35999. var dt = timeMs - this._lastFrameTimeMs;
  36000. this._rollingFrameTime.add(dt);
  36001. }
  36002. this._lastFrameTimeMs = timeMs;
  36003. };
  36004. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36005. /**
  36006. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36007. * @return Average frame time in milliseconds
  36008. */
  36009. get: function () {
  36010. return this._rollingFrameTime.average;
  36011. },
  36012. enumerable: true,
  36013. configurable: true
  36014. });
  36015. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36016. /**
  36017. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36018. * @return Frame time variance in milliseconds squared
  36019. */
  36020. get: function () {
  36021. return this._rollingFrameTime.variance;
  36022. },
  36023. enumerable: true,
  36024. configurable: true
  36025. });
  36026. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36027. /**
  36028. * Returns the frame time of the most recent frame
  36029. * @return Frame time in milliseconds
  36030. */
  36031. get: function () {
  36032. return this._rollingFrameTime.history(0);
  36033. },
  36034. enumerable: true,
  36035. configurable: true
  36036. });
  36037. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36038. /**
  36039. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36040. * @return Framerate in frames per second
  36041. */
  36042. get: function () {
  36043. return 1000.0 / this._rollingFrameTime.average;
  36044. },
  36045. enumerable: true,
  36046. configurable: true
  36047. });
  36048. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36049. /**
  36050. * Returns the average framerate in frames per second using the most recent frame time
  36051. * @return Framerate in frames per second
  36052. */
  36053. get: function () {
  36054. var history = this._rollingFrameTime.history(0);
  36055. if (history === 0) {
  36056. return 0;
  36057. }
  36058. return 1000.0 / history;
  36059. },
  36060. enumerable: true,
  36061. configurable: true
  36062. });
  36063. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36064. /**
  36065. * Returns true if enough samples have been taken to completely fill the sliding window
  36066. * @return true if saturated
  36067. */
  36068. get: function () {
  36069. return this._rollingFrameTime.isSaturated();
  36070. },
  36071. enumerable: true,
  36072. configurable: true
  36073. });
  36074. /**
  36075. * Enables contributions to the sliding window sample set
  36076. */
  36077. PerformanceMonitor.prototype.enable = function () {
  36078. this._enabled = true;
  36079. };
  36080. /**
  36081. * Disables contributions to the sliding window sample set
  36082. * Samples will not be interpolated over the disabled period
  36083. */
  36084. PerformanceMonitor.prototype.disable = function () {
  36085. this._enabled = false;
  36086. //clear last sample to avoid interpolating over the disabled period when next enabled
  36087. this._lastFrameTimeMs = null;
  36088. };
  36089. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36090. /**
  36091. * Returns true if sampling is enabled
  36092. * @return true if enabled
  36093. */
  36094. get: function () {
  36095. return this._enabled;
  36096. },
  36097. enumerable: true,
  36098. configurable: true
  36099. });
  36100. /**
  36101. * Resets performance monitor
  36102. */
  36103. PerformanceMonitor.prototype.reset = function () {
  36104. //clear last sample to avoid interpolating over the disabled period when next enabled
  36105. this._lastFrameTimeMs = null;
  36106. //wipe record
  36107. this._rollingFrameTime.reset();
  36108. };
  36109. return PerformanceMonitor;
  36110. }());
  36111. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36112. /**
  36113. * RollingAverage
  36114. *
  36115. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36116. */
  36117. var RollingAverage = /** @class */ (function () {
  36118. /**
  36119. * constructor
  36120. * @param length The number of samples required to saturate the sliding window
  36121. */
  36122. function RollingAverage(length) {
  36123. this._samples = new Array(length);
  36124. this.reset();
  36125. }
  36126. /**
  36127. * Adds a sample to the sample set
  36128. * @param v The sample value
  36129. */
  36130. RollingAverage.prototype.add = function (v) {
  36131. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36132. var delta;
  36133. //we need to check if we've already wrapped round
  36134. if (this.isSaturated()) {
  36135. //remove bottom of stack from mean
  36136. var bottomValue = this._samples[this._pos];
  36137. delta = bottomValue - this.average;
  36138. this.average -= delta / (this._sampleCount - 1);
  36139. this._m2 -= delta * (bottomValue - this.average);
  36140. }
  36141. else {
  36142. this._sampleCount++;
  36143. }
  36144. //add new value to mean
  36145. delta = v - this.average;
  36146. this.average += delta / (this._sampleCount);
  36147. this._m2 += delta * (v - this.average);
  36148. //set the new variance
  36149. this.variance = this._m2 / (this._sampleCount - 1);
  36150. this._samples[this._pos] = v;
  36151. this._pos++;
  36152. this._pos %= this._samples.length; //positive wrap around
  36153. };
  36154. /**
  36155. * Returns previously added values or null if outside of history or outside the sliding window domain
  36156. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36157. * @return Value previously recorded with add() or null if outside of range
  36158. */
  36159. RollingAverage.prototype.history = function (i) {
  36160. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36161. return 0;
  36162. }
  36163. var i0 = this._wrapPosition(this._pos - 1.0);
  36164. return this._samples[this._wrapPosition(i0 - i)];
  36165. };
  36166. /**
  36167. * Returns true if enough samples have been taken to completely fill the sliding window
  36168. * @return true if sample-set saturated
  36169. */
  36170. RollingAverage.prototype.isSaturated = function () {
  36171. return this._sampleCount >= this._samples.length;
  36172. };
  36173. /**
  36174. * Resets the rolling average (equivalent to 0 samples taken so far)
  36175. */
  36176. RollingAverage.prototype.reset = function () {
  36177. this.average = 0;
  36178. this.variance = 0;
  36179. this._sampleCount = 0;
  36180. this._pos = 0;
  36181. this._m2 = 0;
  36182. };
  36183. /**
  36184. * Wraps a value around the sample range boundaries
  36185. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36186. * @return Wrapped position in sample range
  36187. */
  36188. RollingAverage.prototype._wrapPosition = function (i) {
  36189. var max = this._samples.length;
  36190. return ((i % max) + max) % max;
  36191. };
  36192. return RollingAverage;
  36193. }());
  36194. BABYLON.RollingAverage = RollingAverage;
  36195. })(BABYLON || (BABYLON = {}));
  36196. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36197. var BABYLON;
  36198. (function (BABYLON) {
  36199. /**
  36200. * This groups together the common properties used for image processing either in direct forward pass
  36201. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36202. * or not.
  36203. */
  36204. var ImageProcessingConfiguration = /** @class */ (function () {
  36205. function ImageProcessingConfiguration() {
  36206. /**
  36207. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36208. */
  36209. this.colorCurves = new BABYLON.ColorCurves();
  36210. this._colorCurvesEnabled = false;
  36211. this._colorGradingEnabled = false;
  36212. this._colorGradingWithGreenDepth = true;
  36213. this._colorGradingBGR = true;
  36214. this._exposure = 1.0;
  36215. this._toneMappingEnabled = false;
  36216. this._contrast = 1.0;
  36217. /**
  36218. * Vignette stretch size.
  36219. */
  36220. this.vignetteStretch = 0;
  36221. /**
  36222. * Vignette centre X Offset.
  36223. */
  36224. this.vignetteCentreX = 0;
  36225. /**
  36226. * Vignette centre Y Offset.
  36227. */
  36228. this.vignetteCentreY = 0;
  36229. /**
  36230. * Vignette weight or intensity of the vignette effect.
  36231. */
  36232. this.vignetteWeight = 1.5;
  36233. /**
  36234. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36235. * if vignetteEnabled is set to true.
  36236. */
  36237. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36238. /**
  36239. * Camera field of view used by the Vignette effect.
  36240. */
  36241. this.vignetteCameraFov = 0.5;
  36242. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36243. this._vignetteEnabled = false;
  36244. this._applyByPostProcess = false;
  36245. this._isEnabled = true;
  36246. /**
  36247. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36248. * @type {BABYLON.Observable}
  36249. */
  36250. this.onUpdateParameters = new BABYLON.Observable();
  36251. }
  36252. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36253. /**
  36254. * Gets wether the color curves effect is enabled.
  36255. */
  36256. get: function () {
  36257. return this._colorCurvesEnabled;
  36258. },
  36259. /**
  36260. * Sets wether the color curves effect is enabled.
  36261. */
  36262. set: function (value) {
  36263. if (this._colorCurvesEnabled === value) {
  36264. return;
  36265. }
  36266. this._colorCurvesEnabled = value;
  36267. this._updateParameters();
  36268. },
  36269. enumerable: true,
  36270. configurable: true
  36271. });
  36272. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36273. /**
  36274. * Gets wether the color grading effect is enabled.
  36275. */
  36276. get: function () {
  36277. return this._colorGradingEnabled;
  36278. },
  36279. /**
  36280. * Sets wether the color grading effect is enabled.
  36281. */
  36282. set: function (value) {
  36283. if (this._colorGradingEnabled === value) {
  36284. return;
  36285. }
  36286. this._colorGradingEnabled = value;
  36287. this._updateParameters();
  36288. },
  36289. enumerable: true,
  36290. configurable: true
  36291. });
  36292. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36293. /**
  36294. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36295. */
  36296. get: function () {
  36297. return this._colorGradingWithGreenDepth;
  36298. },
  36299. /**
  36300. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36301. */
  36302. set: function (value) {
  36303. if (this._colorGradingWithGreenDepth === value) {
  36304. return;
  36305. }
  36306. this._colorGradingWithGreenDepth = value;
  36307. this._updateParameters();
  36308. },
  36309. enumerable: true,
  36310. configurable: true
  36311. });
  36312. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36313. /**
  36314. * Gets wether the color grading texture contains BGR values.
  36315. */
  36316. get: function () {
  36317. return this._colorGradingBGR;
  36318. },
  36319. /**
  36320. * Sets wether the color grading texture contains BGR values.
  36321. */
  36322. set: function (value) {
  36323. if (this._colorGradingBGR === value) {
  36324. return;
  36325. }
  36326. this._colorGradingBGR = value;
  36327. this._updateParameters();
  36328. },
  36329. enumerable: true,
  36330. configurable: true
  36331. });
  36332. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36333. /**
  36334. * Gets the Exposure used in the effect.
  36335. */
  36336. get: function () {
  36337. return this._exposure;
  36338. },
  36339. /**
  36340. * Sets the Exposure used in the effect.
  36341. */
  36342. set: function (value) {
  36343. if (this._exposure === value) {
  36344. return;
  36345. }
  36346. this._exposure = value;
  36347. this._updateParameters();
  36348. },
  36349. enumerable: true,
  36350. configurable: true
  36351. });
  36352. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36353. /**
  36354. * Gets wether the tone mapping effect is enabled.
  36355. */
  36356. get: function () {
  36357. return this._toneMappingEnabled;
  36358. },
  36359. /**
  36360. * Sets wether the tone mapping effect is enabled.
  36361. */
  36362. set: function (value) {
  36363. if (this._toneMappingEnabled === value) {
  36364. return;
  36365. }
  36366. this._toneMappingEnabled = value;
  36367. this._updateParameters();
  36368. },
  36369. enumerable: true,
  36370. configurable: true
  36371. });
  36372. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36373. /**
  36374. * Gets the contrast used in the effect.
  36375. */
  36376. get: function () {
  36377. return this._contrast;
  36378. },
  36379. /**
  36380. * Sets the contrast used in the effect.
  36381. */
  36382. set: function (value) {
  36383. if (this._contrast === value) {
  36384. return;
  36385. }
  36386. this._contrast = value;
  36387. this._updateParameters();
  36388. },
  36389. enumerable: true,
  36390. configurable: true
  36391. });
  36392. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36393. /**
  36394. * Gets the vignette blend mode allowing different kind of effect.
  36395. */
  36396. get: function () {
  36397. return this._vignetteBlendMode;
  36398. },
  36399. /**
  36400. * Sets the vignette blend mode allowing different kind of effect.
  36401. */
  36402. set: function (value) {
  36403. if (this._vignetteBlendMode === value) {
  36404. return;
  36405. }
  36406. this._vignetteBlendMode = value;
  36407. this._updateParameters();
  36408. },
  36409. enumerable: true,
  36410. configurable: true
  36411. });
  36412. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36413. /**
  36414. * Gets wether the vignette effect is enabled.
  36415. */
  36416. get: function () {
  36417. return this._vignetteEnabled;
  36418. },
  36419. /**
  36420. * Sets wether the vignette effect is enabled.
  36421. */
  36422. set: function (value) {
  36423. if (this._vignetteEnabled === value) {
  36424. return;
  36425. }
  36426. this._vignetteEnabled = value;
  36427. this._updateParameters();
  36428. },
  36429. enumerable: true,
  36430. configurable: true
  36431. });
  36432. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36433. /**
  36434. * Gets wether the image processing is applied through a post process or not.
  36435. */
  36436. get: function () {
  36437. return this._applyByPostProcess;
  36438. },
  36439. /**
  36440. * Sets wether the image processing is applied through a post process or not.
  36441. */
  36442. set: function (value) {
  36443. if (this._applyByPostProcess === value) {
  36444. return;
  36445. }
  36446. this._applyByPostProcess = value;
  36447. this._updateParameters();
  36448. },
  36449. enumerable: true,
  36450. configurable: true
  36451. });
  36452. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36453. /**
  36454. * Gets wether the image processing is enabled or not.
  36455. */
  36456. get: function () {
  36457. return this._isEnabled;
  36458. },
  36459. /**
  36460. * Sets wether the image processing is enabled or not.
  36461. */
  36462. set: function (value) {
  36463. if (this._isEnabled === value) {
  36464. return;
  36465. }
  36466. this._isEnabled = value;
  36467. this._updateParameters();
  36468. },
  36469. enumerable: true,
  36470. configurable: true
  36471. });
  36472. /**
  36473. * Method called each time the image processing information changes requires to recompile the effect.
  36474. */
  36475. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36476. this.onUpdateParameters.notifyObservers(this);
  36477. };
  36478. ImageProcessingConfiguration.prototype.getClassName = function () {
  36479. return "ImageProcessingConfiguration";
  36480. };
  36481. /**
  36482. * Prepare the list of uniforms associated with the Image Processing effects.
  36483. * @param uniformsList The list of uniforms used in the effect
  36484. * @param defines the list of defines currently in use
  36485. */
  36486. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36487. if (defines.EXPOSURE) {
  36488. uniforms.push("exposureLinear");
  36489. }
  36490. if (defines.CONTRAST) {
  36491. uniforms.push("contrast");
  36492. }
  36493. if (defines.COLORGRADING) {
  36494. uniforms.push("colorTransformSettings");
  36495. }
  36496. if (defines.VIGNETTE) {
  36497. uniforms.push("vInverseScreenSize");
  36498. uniforms.push("vignetteSettings1");
  36499. uniforms.push("vignetteSettings2");
  36500. }
  36501. if (defines.COLORCURVES) {
  36502. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36503. }
  36504. };
  36505. /**
  36506. * Prepare the list of samplers associated with the Image Processing effects.
  36507. * @param uniformsList The list of uniforms used in the effect
  36508. * @param defines the list of defines currently in use
  36509. */
  36510. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36511. if (defines.COLORGRADING) {
  36512. samplersList.push("txColorTransform");
  36513. }
  36514. };
  36515. /**
  36516. * Prepare the list of defines associated to the shader.
  36517. * @param defines the list of defines to complete
  36518. */
  36519. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36520. if (forPostProcess === void 0) { forPostProcess = false; }
  36521. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36522. defines.VIGNETTE = false;
  36523. defines.TONEMAPPING = false;
  36524. defines.CONTRAST = false;
  36525. defines.EXPOSURE = false;
  36526. defines.COLORCURVES = false;
  36527. defines.COLORGRADING = false;
  36528. defines.COLORGRADING3D = false;
  36529. defines.IMAGEPROCESSING = false;
  36530. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36531. return;
  36532. }
  36533. defines.VIGNETTE = this.vignetteEnabled;
  36534. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36535. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36536. defines.TONEMAPPING = this.toneMappingEnabled;
  36537. defines.CONTRAST = (this.contrast !== 1.0);
  36538. defines.EXPOSURE = (this.exposure !== 1.0);
  36539. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36540. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36541. if (defines.COLORGRADING) {
  36542. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36543. }
  36544. else {
  36545. defines.COLORGRADING3D = false;
  36546. }
  36547. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36548. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36549. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36550. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36551. };
  36552. /**
  36553. * Returns true if all the image processing information are ready.
  36554. */
  36555. ImageProcessingConfiguration.prototype.isReady = function () {
  36556. // Color Grading texure can not be none blocking.
  36557. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36558. };
  36559. /**
  36560. * Binds the image processing to the shader.
  36561. * @param effect The effect to bind to
  36562. */
  36563. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36564. if (aspectRatio === void 0) { aspectRatio = 1; }
  36565. // Color Curves
  36566. if (this._colorCurvesEnabled && this.colorCurves) {
  36567. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36568. }
  36569. // Vignette
  36570. if (this._vignetteEnabled) {
  36571. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36572. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36573. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36574. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36575. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36576. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36577. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36578. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36579. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36580. var vignettePower = -2.0 * this.vignetteWeight;
  36581. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36582. }
  36583. // Exposure
  36584. effect.setFloat("exposureLinear", this.exposure);
  36585. // Contrast
  36586. effect.setFloat("contrast", this.contrast);
  36587. // Color transform settings
  36588. if (this.colorGradingTexture) {
  36589. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36590. var textureSize = this.colorGradingTexture.getSize().height;
  36591. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36592. 0.5 / textureSize, // textureOffset
  36593. textureSize, // textureSize
  36594. this.colorGradingTexture.level // weight
  36595. );
  36596. }
  36597. };
  36598. /**
  36599. * Clones the current image processing instance.
  36600. * @return The cloned image processing
  36601. */
  36602. ImageProcessingConfiguration.prototype.clone = function () {
  36603. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36604. };
  36605. /**
  36606. * Serializes the current image processing instance to a json representation.
  36607. * @return a JSON representation
  36608. */
  36609. ImageProcessingConfiguration.prototype.serialize = function () {
  36610. return BABYLON.SerializationHelper.Serialize(this);
  36611. };
  36612. /**
  36613. * Parses the image processing from a json representation.
  36614. * @param source the JSON source to parse
  36615. * @return The parsed image processing
  36616. */
  36617. ImageProcessingConfiguration.Parse = function (source) {
  36618. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36619. };
  36620. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36621. /**
  36622. * Used to apply the vignette as a mix with the pixel color.
  36623. */
  36624. get: function () {
  36625. return this._VIGNETTEMODE_MULTIPLY;
  36626. },
  36627. enumerable: true,
  36628. configurable: true
  36629. });
  36630. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36631. /**
  36632. * Used to apply the vignette as a replacement of the pixel color.
  36633. */
  36634. get: function () {
  36635. return this._VIGNETTEMODE_OPAQUE;
  36636. },
  36637. enumerable: true,
  36638. configurable: true
  36639. });
  36640. // Static constants associated to the image processing.
  36641. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36642. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36643. __decorate([
  36644. BABYLON.serializeAsColorCurves()
  36645. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36646. __decorate([
  36647. BABYLON.serialize()
  36648. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  36649. __decorate([
  36650. BABYLON.serializeAsTexture()
  36651. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  36652. __decorate([
  36653. BABYLON.serialize()
  36654. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  36655. __decorate([
  36656. BABYLON.serialize()
  36657. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  36658. __decorate([
  36659. BABYLON.serialize()
  36660. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  36661. __decorate([
  36662. BABYLON.serialize()
  36663. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  36664. __decorate([
  36665. BABYLON.serialize()
  36666. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  36667. __decorate([
  36668. BABYLON.serialize()
  36669. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  36670. __decorate([
  36671. BABYLON.serialize()
  36672. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  36673. __decorate([
  36674. BABYLON.serialize()
  36675. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  36676. __decorate([
  36677. BABYLON.serialize()
  36678. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  36679. __decorate([
  36680. BABYLON.serialize()
  36681. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  36682. __decorate([
  36683. BABYLON.serializeAsColor4()
  36684. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  36685. __decorate([
  36686. BABYLON.serialize()
  36687. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  36688. __decorate([
  36689. BABYLON.serialize()
  36690. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  36691. __decorate([
  36692. BABYLON.serialize()
  36693. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  36694. __decorate([
  36695. BABYLON.serialize()
  36696. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  36697. __decorate([
  36698. BABYLON.serialize()
  36699. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  36700. return ImageProcessingConfiguration;
  36701. }());
  36702. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  36703. })(BABYLON || (BABYLON = {}));
  36704. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  36705. var BABYLON;
  36706. (function (BABYLON) {
  36707. /**
  36708. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  36709. * It can help converting any input color in a desired output one. This can then be used to create effects
  36710. * from sepia, black and white to sixties or futuristic rendering...
  36711. *
  36712. * The only supported format is currently 3dl.
  36713. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  36714. */
  36715. var ColorGradingTexture = /** @class */ (function (_super) {
  36716. __extends(ColorGradingTexture, _super);
  36717. /**
  36718. * Instantiates a ColorGradingTexture from the following parameters.
  36719. *
  36720. * @param url The location of the color gradind data (currently only supporting 3dl)
  36721. * @param scene The scene the texture will be used in
  36722. */
  36723. function ColorGradingTexture(url, scene) {
  36724. var _this = _super.call(this, scene) || this;
  36725. if (!url) {
  36726. return _this;
  36727. }
  36728. _this._engine = scene.getEngine();
  36729. _this._textureMatrix = BABYLON.Matrix.Identity();
  36730. _this.name = url;
  36731. _this.url = url;
  36732. _this.hasAlpha = false;
  36733. _this.isCube = false;
  36734. _this.is3D = _this._engine.webGLVersion > 1;
  36735. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36736. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36737. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36738. _this.anisotropicFilteringLevel = 1;
  36739. _this._texture = _this._getFromCache(url, true);
  36740. if (!_this._texture) {
  36741. if (!scene.useDelayedTextureLoading) {
  36742. _this.loadTexture();
  36743. }
  36744. else {
  36745. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36746. }
  36747. }
  36748. return _this;
  36749. }
  36750. /**
  36751. * Returns the texture matrix used in most of the material.
  36752. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  36753. */
  36754. ColorGradingTexture.prototype.getTextureMatrix = function () {
  36755. return this._textureMatrix;
  36756. };
  36757. /**
  36758. * Occurs when the file being loaded is a .3dl LUT file.
  36759. */
  36760. ColorGradingTexture.prototype.load3dlTexture = function () {
  36761. var engine = this._engine;
  36762. var texture;
  36763. if (engine.webGLVersion === 1) {
  36764. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36765. }
  36766. else {
  36767. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36768. }
  36769. this._texture = texture;
  36770. var callback = function (text) {
  36771. if (typeof text !== "string") {
  36772. return;
  36773. }
  36774. var data = null;
  36775. var tempData = null;
  36776. var line;
  36777. var lines = text.split('\n');
  36778. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  36779. var maxColor = 0;
  36780. for (var i = 0; i < lines.length; i++) {
  36781. line = lines[i];
  36782. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  36783. continue;
  36784. if (line.indexOf('#') === 0)
  36785. continue;
  36786. var words = line.split(" ");
  36787. if (size === 0) {
  36788. // Number of space + one
  36789. size = words.length;
  36790. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  36791. tempData = new Float32Array(size * size * size * 4);
  36792. continue;
  36793. }
  36794. if (size != 0) {
  36795. var r = Math.max(parseInt(words[0]), 0);
  36796. var g = Math.max(parseInt(words[1]), 0);
  36797. var b = Math.max(parseInt(words[2]), 0);
  36798. maxColor = Math.max(r, maxColor);
  36799. maxColor = Math.max(g, maxColor);
  36800. maxColor = Math.max(b, maxColor);
  36801. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  36802. if (tempData) {
  36803. tempData[pixelStorageIndex + 0] = r;
  36804. tempData[pixelStorageIndex + 1] = g;
  36805. tempData[pixelStorageIndex + 2] = b;
  36806. }
  36807. pixelIndexSlice++;
  36808. if (pixelIndexSlice % size == 0) {
  36809. pixelIndexH++;
  36810. pixelIndexSlice = 0;
  36811. if (pixelIndexH % size == 0) {
  36812. pixelIndexW++;
  36813. pixelIndexH = 0;
  36814. }
  36815. }
  36816. }
  36817. }
  36818. if (tempData && data) {
  36819. for (var i = 0; i < tempData.length; i++) {
  36820. if (i > 0 && (i + 1) % 4 === 0) {
  36821. data[i] = 255;
  36822. }
  36823. else {
  36824. var value = tempData[i];
  36825. data[i] = (value / maxColor * 255);
  36826. }
  36827. }
  36828. }
  36829. if (texture.is3D) {
  36830. texture.updateSize(size, size, size);
  36831. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36832. }
  36833. else {
  36834. texture.updateSize(size * size, size);
  36835. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36836. }
  36837. };
  36838. var scene = this.getScene();
  36839. if (scene) {
  36840. scene._loadFile(this.url, callback);
  36841. }
  36842. else {
  36843. this._engine._loadFile(this.url, callback);
  36844. }
  36845. return this._texture;
  36846. };
  36847. /**
  36848. * Starts the loading process of the texture.
  36849. */
  36850. ColorGradingTexture.prototype.loadTexture = function () {
  36851. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  36852. this.load3dlTexture();
  36853. }
  36854. };
  36855. /**
  36856. * Clones the color gradind texture.
  36857. */
  36858. ColorGradingTexture.prototype.clone = function () {
  36859. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  36860. // Base texture
  36861. newTexture.level = this.level;
  36862. return newTexture;
  36863. };
  36864. /**
  36865. * Called during delayed load for textures.
  36866. */
  36867. ColorGradingTexture.prototype.delayLoad = function () {
  36868. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  36869. return;
  36870. }
  36871. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36872. this._texture = this._getFromCache(this.url, true);
  36873. if (!this._texture) {
  36874. this.loadTexture();
  36875. }
  36876. };
  36877. /**
  36878. * Parses a color grading texture serialized by Babylon.
  36879. * @param parsedTexture The texture information being parsedTexture
  36880. * @param scene The scene to load the texture in
  36881. * @param rootUrl The root url of the data assets to load
  36882. * @return A color gradind texture
  36883. */
  36884. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  36885. var texture = null;
  36886. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  36887. texture = new ColorGradingTexture(parsedTexture.name, scene);
  36888. texture.name = parsedTexture.name;
  36889. texture.level = parsedTexture.level;
  36890. }
  36891. return texture;
  36892. };
  36893. /**
  36894. * Serializes the LUT texture to json format.
  36895. */
  36896. ColorGradingTexture.prototype.serialize = function () {
  36897. if (!this.name) {
  36898. return null;
  36899. }
  36900. var serializationObject = {};
  36901. serializationObject.name = this.name;
  36902. serializationObject.level = this.level;
  36903. serializationObject.customType = "BABYLON.ColorGradingTexture";
  36904. return serializationObject;
  36905. };
  36906. /**
  36907. * Empty line regex stored for GC.
  36908. */
  36909. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  36910. return ColorGradingTexture;
  36911. }(BABYLON.BaseTexture));
  36912. BABYLON.ColorGradingTexture = ColorGradingTexture;
  36913. })(BABYLON || (BABYLON = {}));
  36914. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  36915. var BABYLON;
  36916. (function (BABYLON) {
  36917. /**
  36918. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36919. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36920. * 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;
  36921. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36922. */
  36923. var ColorCurves = /** @class */ (function () {
  36924. function ColorCurves() {
  36925. this._dirty = true;
  36926. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  36927. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  36928. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  36929. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  36930. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  36931. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  36932. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  36933. this._globalHue = 30;
  36934. this._globalDensity = 0;
  36935. this._globalSaturation = 0;
  36936. this._globalExposure = 0;
  36937. this._highlightsHue = 30;
  36938. this._highlightsDensity = 0;
  36939. this._highlightsSaturation = 0;
  36940. this._highlightsExposure = 0;
  36941. this._midtonesHue = 30;
  36942. this._midtonesDensity = 0;
  36943. this._midtonesSaturation = 0;
  36944. this._midtonesExposure = 0;
  36945. this._shadowsHue = 30;
  36946. this._shadowsDensity = 0;
  36947. this._shadowsSaturation = 0;
  36948. this._shadowsExposure = 0;
  36949. }
  36950. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  36951. /**
  36952. * Gets the global Hue value.
  36953. * 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).
  36954. */
  36955. get: function () {
  36956. return this._globalHue;
  36957. },
  36958. /**
  36959. * Sets the global Hue value.
  36960. * 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).
  36961. */
  36962. set: function (value) {
  36963. this._globalHue = value;
  36964. this._dirty = true;
  36965. },
  36966. enumerable: true,
  36967. configurable: true
  36968. });
  36969. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  36970. /**
  36971. * Gets the global Density value.
  36972. * 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.
  36973. * Values less than zero provide a filter of opposite hue.
  36974. */
  36975. get: function () {
  36976. return this._globalDensity;
  36977. },
  36978. /**
  36979. * Sets the global Density value.
  36980. * 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.
  36981. * Values less than zero provide a filter of opposite hue.
  36982. */
  36983. set: function (value) {
  36984. this._globalDensity = value;
  36985. this._dirty = true;
  36986. },
  36987. enumerable: true,
  36988. configurable: true
  36989. });
  36990. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  36991. /**
  36992. * Gets the global Saturation value.
  36993. * 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.
  36994. */
  36995. get: function () {
  36996. return this._globalSaturation;
  36997. },
  36998. /**
  36999. * Sets the global Saturation value.
  37000. * 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.
  37001. */
  37002. set: function (value) {
  37003. this._globalSaturation = value;
  37004. this._dirty = true;
  37005. },
  37006. enumerable: true,
  37007. configurable: true
  37008. });
  37009. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37010. /**
  37011. * Gets the highlights Hue value.
  37012. * 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).
  37013. */
  37014. get: function () {
  37015. return this._highlightsHue;
  37016. },
  37017. /**
  37018. * Sets the highlights Hue value.
  37019. * 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).
  37020. */
  37021. set: function (value) {
  37022. this._highlightsHue = value;
  37023. this._dirty = true;
  37024. },
  37025. enumerable: true,
  37026. configurable: true
  37027. });
  37028. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37029. /**
  37030. * Gets the highlights Density value.
  37031. * 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.
  37032. * Values less than zero provide a filter of opposite hue.
  37033. */
  37034. get: function () {
  37035. return this._highlightsDensity;
  37036. },
  37037. /**
  37038. * Sets the highlights Density value.
  37039. * 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.
  37040. * Values less than zero provide a filter of opposite hue.
  37041. */
  37042. set: function (value) {
  37043. this._highlightsDensity = value;
  37044. this._dirty = true;
  37045. },
  37046. enumerable: true,
  37047. configurable: true
  37048. });
  37049. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37050. /**
  37051. * Gets the highlights Saturation value.
  37052. * 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.
  37053. */
  37054. get: function () {
  37055. return this._highlightsSaturation;
  37056. },
  37057. /**
  37058. * Sets the highlights Saturation value.
  37059. * 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.
  37060. */
  37061. set: function (value) {
  37062. this._highlightsSaturation = value;
  37063. this._dirty = true;
  37064. },
  37065. enumerable: true,
  37066. configurable: true
  37067. });
  37068. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37069. /**
  37070. * Gets the highlights Exposure value.
  37071. * 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.
  37072. */
  37073. get: function () {
  37074. return this._highlightsExposure;
  37075. },
  37076. /**
  37077. * Sets the highlights Exposure value.
  37078. * 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.
  37079. */
  37080. set: function (value) {
  37081. this._highlightsExposure = value;
  37082. this._dirty = true;
  37083. },
  37084. enumerable: true,
  37085. configurable: true
  37086. });
  37087. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37088. /**
  37089. * Gets the midtones Hue value.
  37090. * 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).
  37091. */
  37092. get: function () {
  37093. return this._midtonesHue;
  37094. },
  37095. /**
  37096. * Sets the midtones Hue value.
  37097. * 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).
  37098. */
  37099. set: function (value) {
  37100. this._midtonesHue = value;
  37101. this._dirty = true;
  37102. },
  37103. enumerable: true,
  37104. configurable: true
  37105. });
  37106. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37107. /**
  37108. * Gets the midtones Density value.
  37109. * 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.
  37110. * Values less than zero provide a filter of opposite hue.
  37111. */
  37112. get: function () {
  37113. return this._midtonesDensity;
  37114. },
  37115. /**
  37116. * Sets the midtones Density value.
  37117. * 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.
  37118. * Values less than zero provide a filter of opposite hue.
  37119. */
  37120. set: function (value) {
  37121. this._midtonesDensity = value;
  37122. this._dirty = true;
  37123. },
  37124. enumerable: true,
  37125. configurable: true
  37126. });
  37127. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37128. /**
  37129. * Gets the midtones Saturation value.
  37130. * 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.
  37131. */
  37132. get: function () {
  37133. return this._midtonesSaturation;
  37134. },
  37135. /**
  37136. * Sets the midtones Saturation value.
  37137. * 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.
  37138. */
  37139. set: function (value) {
  37140. this._midtonesSaturation = value;
  37141. this._dirty = true;
  37142. },
  37143. enumerable: true,
  37144. configurable: true
  37145. });
  37146. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37147. /**
  37148. * Gets the midtones Exposure value.
  37149. * 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.
  37150. */
  37151. get: function () {
  37152. return this._midtonesExposure;
  37153. },
  37154. /**
  37155. * Sets the midtones Exposure value.
  37156. * 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.
  37157. */
  37158. set: function (value) {
  37159. this._midtonesExposure = value;
  37160. this._dirty = true;
  37161. },
  37162. enumerable: true,
  37163. configurable: true
  37164. });
  37165. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37166. /**
  37167. * Gets the shadows Hue value.
  37168. * 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).
  37169. */
  37170. get: function () {
  37171. return this._shadowsHue;
  37172. },
  37173. /**
  37174. * Sets the shadows Hue value.
  37175. * 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).
  37176. */
  37177. set: function (value) {
  37178. this._shadowsHue = value;
  37179. this._dirty = true;
  37180. },
  37181. enumerable: true,
  37182. configurable: true
  37183. });
  37184. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37185. /**
  37186. * Gets the shadows Density value.
  37187. * 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.
  37188. * Values less than zero provide a filter of opposite hue.
  37189. */
  37190. get: function () {
  37191. return this._shadowsDensity;
  37192. },
  37193. /**
  37194. * Sets the shadows Density value.
  37195. * 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.
  37196. * Values less than zero provide a filter of opposite hue.
  37197. */
  37198. set: function (value) {
  37199. this._shadowsDensity = value;
  37200. this._dirty = true;
  37201. },
  37202. enumerable: true,
  37203. configurable: true
  37204. });
  37205. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37206. /**
  37207. * Gets the shadows Saturation value.
  37208. * 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.
  37209. */
  37210. get: function () {
  37211. return this._shadowsSaturation;
  37212. },
  37213. /**
  37214. * Sets the shadows Saturation value.
  37215. * 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.
  37216. */
  37217. set: function (value) {
  37218. this._shadowsSaturation = value;
  37219. this._dirty = true;
  37220. },
  37221. enumerable: true,
  37222. configurable: true
  37223. });
  37224. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37225. /**
  37226. * Gets the shadows Exposure value.
  37227. * 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.
  37228. */
  37229. get: function () {
  37230. return this._shadowsExposure;
  37231. },
  37232. /**
  37233. * Sets the shadows Exposure value.
  37234. * 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.
  37235. */
  37236. set: function (value) {
  37237. this._shadowsExposure = value;
  37238. this._dirty = true;
  37239. },
  37240. enumerable: true,
  37241. configurable: true
  37242. });
  37243. ColorCurves.prototype.getClassName = function () {
  37244. return "ColorCurves";
  37245. };
  37246. /**
  37247. * Binds the color curves to the shader.
  37248. * @param colorCurves The color curve to bind
  37249. * @param effect The effect to bind to
  37250. */
  37251. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37252. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37253. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37254. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37255. if (colorCurves._dirty) {
  37256. colorCurves._dirty = false;
  37257. // Fill in global info.
  37258. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37259. // Compute highlights info.
  37260. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37261. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37262. // Compute midtones info.
  37263. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37264. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37265. // Compute shadows info.
  37266. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37267. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37268. // Compute deltas (neutral is midtones).
  37269. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37270. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37271. }
  37272. if (effect) {
  37273. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37274. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37275. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37276. }
  37277. };
  37278. /**
  37279. * Prepare the list of uniforms associated with the ColorCurves effects.
  37280. * @param uniformsList The list of uniforms used in the effect
  37281. */
  37282. ColorCurves.PrepareUniforms = function (uniformsList) {
  37283. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37284. };
  37285. /**
  37286. * Returns color grading data based on a hue, density, saturation and exposure value.
  37287. * @param filterHue The hue of the color filter.
  37288. * @param filterDensity The density of the color filter.
  37289. * @param saturation The saturation.
  37290. * @param exposure The exposure.
  37291. * @param result The result data container.
  37292. */
  37293. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37294. if (hue == null) {
  37295. return;
  37296. }
  37297. hue = ColorCurves.clamp(hue, 0, 360);
  37298. density = ColorCurves.clamp(density, -100, 100);
  37299. saturation = ColorCurves.clamp(saturation, -100, 100);
  37300. exposure = ColorCurves.clamp(exposure, -100, 100);
  37301. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37302. // so that the maximum filter density is only 50% control. This provides fine control
  37303. // for small values and reasonable range.
  37304. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37305. density *= 0.5;
  37306. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37307. if (density < 0) {
  37308. density *= -1;
  37309. hue = (hue + 180) % 360;
  37310. }
  37311. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37312. result.scaleToRef(2, result);
  37313. result.a = 1 + 0.01 * saturation;
  37314. };
  37315. /**
  37316. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37317. * @param value The input slider value in range [-100,100].
  37318. * @returns Adjusted value.
  37319. */
  37320. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37321. value /= 100;
  37322. var x = Math.abs(value);
  37323. x = Math.pow(x, 2);
  37324. if (value < 0) {
  37325. x *= -1;
  37326. }
  37327. x *= 100;
  37328. return x;
  37329. };
  37330. /**
  37331. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37332. * @param hue The hue (H) input.
  37333. * @param saturation The saturation (S) input.
  37334. * @param brightness The brightness (B) input.
  37335. * @result An RGBA color represented as Vector4.
  37336. */
  37337. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37338. var h = ColorCurves.clamp(hue, 0, 360);
  37339. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37340. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37341. if (s === 0) {
  37342. result.r = v;
  37343. result.g = v;
  37344. result.b = v;
  37345. }
  37346. else {
  37347. // sector 0 to 5
  37348. h /= 60;
  37349. var i = Math.floor(h);
  37350. // fractional part of h
  37351. var f = h - i;
  37352. var p = v * (1 - s);
  37353. var q = v * (1 - s * f);
  37354. var t = v * (1 - s * (1 - f));
  37355. switch (i) {
  37356. case 0:
  37357. result.r = v;
  37358. result.g = t;
  37359. result.b = p;
  37360. break;
  37361. case 1:
  37362. result.r = q;
  37363. result.g = v;
  37364. result.b = p;
  37365. break;
  37366. case 2:
  37367. result.r = p;
  37368. result.g = v;
  37369. result.b = t;
  37370. break;
  37371. case 3:
  37372. result.r = p;
  37373. result.g = q;
  37374. result.b = v;
  37375. break;
  37376. case 4:
  37377. result.r = t;
  37378. result.g = p;
  37379. result.b = v;
  37380. break;
  37381. default:// case 5:
  37382. result.r = v;
  37383. result.g = p;
  37384. result.b = q;
  37385. break;
  37386. }
  37387. }
  37388. result.a = 1;
  37389. };
  37390. /**
  37391. * Returns a value clamped between min and max
  37392. * @param value The value to clamp
  37393. * @param min The minimum of value
  37394. * @param max The maximum of value
  37395. * @returns The clamped value.
  37396. */
  37397. ColorCurves.clamp = function (value, min, max) {
  37398. return Math.min(Math.max(value, min), max);
  37399. };
  37400. /**
  37401. * Clones the current color curve instance.
  37402. * @return The cloned curves
  37403. */
  37404. ColorCurves.prototype.clone = function () {
  37405. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37406. };
  37407. /**
  37408. * Serializes the current color curve instance to a json representation.
  37409. * @return a JSON representation
  37410. */
  37411. ColorCurves.prototype.serialize = function () {
  37412. return BABYLON.SerializationHelper.Serialize(this);
  37413. };
  37414. /**
  37415. * Parses the color curve from a json representation.
  37416. * @param source the JSON source to parse
  37417. * @return The parsed curves
  37418. */
  37419. ColorCurves.Parse = function (source) {
  37420. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37421. };
  37422. __decorate([
  37423. BABYLON.serialize()
  37424. ], ColorCurves.prototype, "_globalHue", void 0);
  37425. __decorate([
  37426. BABYLON.serialize()
  37427. ], ColorCurves.prototype, "_globalDensity", void 0);
  37428. __decorate([
  37429. BABYLON.serialize()
  37430. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37431. __decorate([
  37432. BABYLON.serialize()
  37433. ], ColorCurves.prototype, "_globalExposure", void 0);
  37434. __decorate([
  37435. BABYLON.serialize()
  37436. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37437. __decorate([
  37438. BABYLON.serialize()
  37439. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37440. __decorate([
  37441. BABYLON.serialize()
  37442. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37443. __decorate([
  37444. BABYLON.serialize()
  37445. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37446. __decorate([
  37447. BABYLON.serialize()
  37448. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37449. __decorate([
  37450. BABYLON.serialize()
  37451. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37452. __decorate([
  37453. BABYLON.serialize()
  37454. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37455. __decorate([
  37456. BABYLON.serialize()
  37457. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37458. return ColorCurves;
  37459. }());
  37460. BABYLON.ColorCurves = ColorCurves;
  37461. })(BABYLON || (BABYLON = {}));
  37462. //# sourceMappingURL=babylon.colorCurves.js.map
  37463. //# sourceMappingURL=babylon.behavior.js.map
  37464. var BABYLON;
  37465. (function (BABYLON) {
  37466. /**
  37467. * "Static Class" containing the most commonly used helper while dealing with material for
  37468. * rendering purpose.
  37469. *
  37470. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37471. *
  37472. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37473. */
  37474. var MaterialHelper = /** @class */ (function () {
  37475. function MaterialHelper() {
  37476. }
  37477. /**
  37478. * Bind the current view position to an effect.
  37479. * @param effect The effect to be bound
  37480. * @param scene The scene the eyes position is used from
  37481. */
  37482. MaterialHelper.BindEyePosition = function (effect, scene) {
  37483. if (scene._forcedViewPosition) {
  37484. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37485. return;
  37486. }
  37487. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37488. };
  37489. /**
  37490. * Helps preparing the defines values about the UVs in used in the effect.
  37491. * UVs are shared as much as we can accross chanels in the shaders.
  37492. * @param texture The texture we are preparing the UVs for
  37493. * @param defines The defines to update
  37494. * @param key The chanel key "diffuse", "specular"... used in the shader
  37495. */
  37496. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37497. defines._needUVs = true;
  37498. defines[key] = true;
  37499. if (texture.getTextureMatrix().isIdentity(true)) {
  37500. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37501. if (texture.coordinatesIndex === 0) {
  37502. defines["MAINUV1"] = true;
  37503. }
  37504. else {
  37505. defines["MAINUV2"] = true;
  37506. }
  37507. }
  37508. else {
  37509. defines[key + "DIRECTUV"] = 0;
  37510. }
  37511. };
  37512. /**
  37513. * Binds a texture matrix value to its corrsponding uniform
  37514. * @param texture The texture to bind the matrix for
  37515. * @param uniformBuffer The uniform buffer receivin the data
  37516. * @param key The chanel key "diffuse", "specular"... used in the shader
  37517. */
  37518. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37519. var matrix = texture.getTextureMatrix();
  37520. if (!matrix.isIdentity(true)) {
  37521. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37522. }
  37523. };
  37524. /**
  37525. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37526. * @param mesh defines the current mesh
  37527. * @param scene defines the current scene
  37528. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37529. * @param pointsCloud defines if point cloud rendering has to be turned on
  37530. * @param fogEnabled defines if fog has to be turned on
  37531. * @param alphaTest defines if alpha testing has to be turned on
  37532. * @param defines defines the current list of defines
  37533. */
  37534. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37535. if (defines._areMiscDirty) {
  37536. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37537. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37538. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37539. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37540. defines["ALPHATEST"] = alphaTest;
  37541. }
  37542. };
  37543. /**
  37544. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37545. * @param scene defines the current scene
  37546. * @param engine defines the current engine
  37547. * @param defines specifies the list of active defines
  37548. * @param useInstances defines if instances have to be turned on
  37549. * @param useClipPlane defines if clip plane have to be turned on
  37550. */
  37551. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  37552. if (useClipPlane === void 0) { useClipPlane = null; }
  37553. var changed = false;
  37554. if (useClipPlane == null) {
  37555. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  37556. }
  37557. if (defines["CLIPPLANE"] !== useClipPlane) {
  37558. defines["CLIPPLANE"] = useClipPlane;
  37559. changed = true;
  37560. }
  37561. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37562. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37563. changed = true;
  37564. }
  37565. if (defines["INSTANCES"] !== useInstances) {
  37566. defines["INSTANCES"] = useInstances;
  37567. changed = true;
  37568. }
  37569. if (changed) {
  37570. defines.markAsUnprocessed();
  37571. }
  37572. };
  37573. /**
  37574. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37575. * @param mesh The mesh containing the geometry data we will draw
  37576. * @param defines The defines to update
  37577. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37578. * @param useBones Precise whether bones should be used or not (override mesh info)
  37579. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37580. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37581. * @returns false if defines are considered not dirty and have not been checked
  37582. */
  37583. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37584. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37585. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37586. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37587. return false;
  37588. }
  37589. defines._normals = defines._needNormals;
  37590. defines._uvs = defines._needUVs;
  37591. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37592. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37593. defines["TANGENT"] = true;
  37594. }
  37595. if (defines._needUVs) {
  37596. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37597. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37598. }
  37599. else {
  37600. defines["UV1"] = false;
  37601. defines["UV2"] = false;
  37602. }
  37603. if (useVertexColor) {
  37604. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37605. defines["VERTEXCOLOR"] = hasVertexColors;
  37606. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37607. }
  37608. if (useBones) {
  37609. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37610. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37611. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37612. }
  37613. else {
  37614. defines["NUM_BONE_INFLUENCERS"] = 0;
  37615. defines["BonesPerMesh"] = 0;
  37616. }
  37617. }
  37618. if (useMorphTargets) {
  37619. var manager = mesh.morphTargetManager;
  37620. if (manager) {
  37621. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37622. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37623. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37624. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37625. }
  37626. else {
  37627. defines["MORPHTARGETS_TANGENT"] = false;
  37628. defines["MORPHTARGETS_NORMAL"] = false;
  37629. defines["MORPHTARGETS"] = false;
  37630. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37631. }
  37632. }
  37633. return true;
  37634. };
  37635. /**
  37636. * Prepares the defines related to the light information passed in parameter
  37637. * @param scene The scene we are intending to draw
  37638. * @param mesh The mesh the effect is compiling for
  37639. * @param defines The defines to update
  37640. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37641. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37642. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37643. * @returns true if normals will be required for the rest of the effect
  37644. */
  37645. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37646. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37647. if (disableLighting === void 0) { disableLighting = false; }
  37648. if (!defines._areLightsDirty) {
  37649. return defines._needNormals;
  37650. }
  37651. var lightIndex = 0;
  37652. var needNormals = false;
  37653. var needRebuild = false;
  37654. var lightmapMode = false;
  37655. var shadowEnabled = false;
  37656. var specularEnabled = false;
  37657. if (scene.lightsEnabled && !disableLighting) {
  37658. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  37659. var light = _a[_i];
  37660. needNormals = true;
  37661. if (defines["LIGHT" + lightIndex] === undefined) {
  37662. needRebuild = true;
  37663. }
  37664. defines["LIGHT" + lightIndex] = true;
  37665. defines["SPOTLIGHT" + lightIndex] = false;
  37666. defines["HEMILIGHT" + lightIndex] = false;
  37667. defines["POINTLIGHT" + lightIndex] = false;
  37668. defines["DIRLIGHT" + lightIndex] = false;
  37669. var type;
  37670. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  37671. type = "SPOTLIGHT" + lightIndex;
  37672. var spotLight = light;
  37673. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  37674. }
  37675. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  37676. type = "HEMILIGHT" + lightIndex;
  37677. }
  37678. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  37679. type = "POINTLIGHT" + lightIndex;
  37680. }
  37681. else {
  37682. type = "DIRLIGHT" + lightIndex;
  37683. }
  37684. defines[type] = true;
  37685. // Specular
  37686. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  37687. specularEnabled = true;
  37688. }
  37689. // Shadows
  37690. defines["SHADOW" + lightIndex] = false;
  37691. defines["SHADOWPCF" + lightIndex] = false;
  37692. defines["SHADOWESM" + lightIndex] = false;
  37693. defines["SHADOWCUBE" + lightIndex] = false;
  37694. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  37695. var shadowGenerator = light.getShadowGenerator();
  37696. if (shadowGenerator) {
  37697. shadowEnabled = true;
  37698. shadowGenerator.prepareDefines(defines, lightIndex);
  37699. }
  37700. }
  37701. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  37702. lightmapMode = true;
  37703. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  37704. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  37705. }
  37706. else {
  37707. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  37708. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  37709. }
  37710. lightIndex++;
  37711. if (lightIndex === maxSimultaneousLights)
  37712. break;
  37713. }
  37714. }
  37715. defines["SPECULARTERM"] = specularEnabled;
  37716. defines["SHADOWS"] = shadowEnabled;
  37717. // Resetting all other lights if any
  37718. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  37719. if (defines["LIGHT" + index] !== undefined) {
  37720. defines["LIGHT" + index] = false;
  37721. defines["HEMILIGHT" + lightIndex] = false;
  37722. defines["POINTLIGHT" + lightIndex] = false;
  37723. defines["DIRLIGHT" + lightIndex] = false;
  37724. defines["SPOTLIGHT" + lightIndex] = false;
  37725. defines["SHADOW" + lightIndex] = false;
  37726. }
  37727. }
  37728. var caps = scene.getEngine().getCaps();
  37729. if (defines["SHADOWFLOAT"] === undefined) {
  37730. needRebuild = true;
  37731. }
  37732. defines["SHADOWFLOAT"] = shadowEnabled &&
  37733. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  37734. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  37735. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  37736. if (needRebuild) {
  37737. defines.rebuild();
  37738. }
  37739. return needNormals;
  37740. };
  37741. /**
  37742. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  37743. * that won t be acctive due to defines being turned off.
  37744. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  37745. * @param samplersList The samplers list
  37746. * @param defines The defines helping in the list generation
  37747. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  37748. */
  37749. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  37750. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37751. var uniformsList;
  37752. var uniformBuffersList = null;
  37753. if (uniformsListOrOptions.uniformsNames) {
  37754. var options = uniformsListOrOptions;
  37755. uniformsList = options.uniformsNames;
  37756. uniformBuffersList = options.uniformBuffersNames;
  37757. samplersList = options.samplers;
  37758. defines = options.defines;
  37759. maxSimultaneousLights = options.maxSimultaneousLights;
  37760. }
  37761. else {
  37762. uniformsList = uniformsListOrOptions;
  37763. if (!samplersList) {
  37764. samplersList = [];
  37765. }
  37766. }
  37767. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37768. if (!defines["LIGHT" + lightIndex]) {
  37769. break;
  37770. }
  37771. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  37772. if (uniformBuffersList) {
  37773. uniformBuffersList.push("Light" + lightIndex);
  37774. }
  37775. samplersList.push("shadowSampler" + lightIndex);
  37776. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  37777. samplersList.push("projectionLightSampler" + lightIndex);
  37778. uniformsList.push("textureProjectionMatrix" + lightIndex);
  37779. }
  37780. }
  37781. if (defines["NUM_MORPH_INFLUENCERS"]) {
  37782. uniformsList.push("morphTargetInfluences");
  37783. }
  37784. };
  37785. /**
  37786. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  37787. * @param defines The defines to update while falling back
  37788. * @param fallbacks The authorized effect fallbacks
  37789. * @param maxSimultaneousLights The maximum number of lights allowed
  37790. * @param rank the current rank of the Effect
  37791. * @returns The newly affected rank
  37792. */
  37793. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  37794. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37795. if (rank === void 0) { rank = 0; }
  37796. var lightFallbackRank = 0;
  37797. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37798. if (!defines["LIGHT" + lightIndex]) {
  37799. break;
  37800. }
  37801. if (lightIndex > 0) {
  37802. lightFallbackRank = rank + lightIndex;
  37803. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  37804. }
  37805. if (!defines["SHADOWS"]) {
  37806. if (defines["SHADOW" + lightIndex]) {
  37807. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  37808. }
  37809. if (defines["SHADOWPCF" + lightIndex]) {
  37810. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  37811. }
  37812. if (defines["SHADOWESM" + lightIndex]) {
  37813. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  37814. }
  37815. }
  37816. }
  37817. return lightFallbackRank++;
  37818. };
  37819. /**
  37820. * Prepares the list of attributes required for morph targets according to the effect defines.
  37821. * @param attribs The current list of supported attribs
  37822. * @param mesh The mesh to prepare the morph targets attributes for
  37823. * @param defines The current Defines of the effect
  37824. */
  37825. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  37826. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  37827. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  37828. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  37829. var manager = mesh.morphTargetManager;
  37830. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  37831. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  37832. for (var index = 0; index < influencers; index++) {
  37833. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  37834. if (normal) {
  37835. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  37836. }
  37837. if (tangent) {
  37838. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  37839. }
  37840. if (attribs.length > maxAttributesCount) {
  37841. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  37842. }
  37843. }
  37844. }
  37845. };
  37846. /**
  37847. * Prepares the list of attributes required for bones according to the effect defines.
  37848. * @param attribs The current list of supported attribs
  37849. * @param mesh The mesh to prepare the bones attributes for
  37850. * @param defines The current Defines of the effect
  37851. * @param fallbacks The current efffect fallback strategy
  37852. */
  37853. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  37854. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  37855. fallbacks.addCPUSkinningFallback(0, mesh);
  37856. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37857. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37858. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  37859. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37860. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37861. }
  37862. }
  37863. };
  37864. /**
  37865. * Prepares the list of attributes required for instances according to the effect defines.
  37866. * @param attribs The current list of supported attribs
  37867. * @param defines The current Defines of the effect
  37868. */
  37869. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  37870. if (defines["INSTANCES"]) {
  37871. attribs.push("world0");
  37872. attribs.push("world1");
  37873. attribs.push("world2");
  37874. attribs.push("world3");
  37875. }
  37876. };
  37877. /**
  37878. * Binds the light shadow information to the effect for the given mesh.
  37879. * @param light The light containing the generator
  37880. * @param scene The scene the lights belongs to
  37881. * @param mesh The mesh we are binding the information to render
  37882. * @param lightIndex The light index in the effect used to render the mesh
  37883. * @param effect The effect we are binding the data to
  37884. */
  37885. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  37886. if (light.shadowEnabled && mesh.receiveShadows) {
  37887. var shadowGenerator = light.getShadowGenerator();
  37888. if (shadowGenerator) {
  37889. shadowGenerator.bindShadowLight(lightIndex, effect);
  37890. }
  37891. }
  37892. };
  37893. /**
  37894. * Binds the light information to the effect.
  37895. * @param light The light containing the generator
  37896. * @param effect The effect we are binding the data to
  37897. * @param lightIndex The light index in the effect used to render
  37898. */
  37899. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  37900. light.transferToEffect(effect, lightIndex + "");
  37901. };
  37902. /**
  37903. * Binds the lights information from the scene to the effect for the given mesh.
  37904. * @param scene The scene the lights belongs to
  37905. * @param mesh The mesh we are binding the information to render
  37906. * @param effect The effect we are binding the data to
  37907. * @param defines The generated defines for the effect
  37908. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  37909. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  37910. */
  37911. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  37912. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37913. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  37914. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  37915. for (var i = 0; i < len; i++) {
  37916. var light = mesh._lightSources[i];
  37917. var iAsString = i.toString();
  37918. var scaledIntensity = light.getScaledIntensity();
  37919. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  37920. MaterialHelper.BindLightProperties(light, effect, i);
  37921. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  37922. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  37923. if (defines["SPECULARTERM"]) {
  37924. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  37925. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  37926. }
  37927. // Shadows
  37928. if (scene.shadowsEnabled) {
  37929. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  37930. }
  37931. light._uniformBuffer.update();
  37932. }
  37933. };
  37934. /**
  37935. * Binds the fog information from the scene to the effect for the given mesh.
  37936. * @param scene The scene the lights belongs to
  37937. * @param mesh The mesh we are binding the information to render
  37938. * @param effect The effect we are binding the data to
  37939. */
  37940. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  37941. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  37942. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  37943. effect.setColor3("vFogColor", scene.fogColor);
  37944. }
  37945. };
  37946. /**
  37947. * Binds the bones information from the mesh to the effect.
  37948. * @param mesh The mesh we are binding the information to render
  37949. * @param effect The effect we are binding the data to
  37950. */
  37951. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  37952. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37953. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  37954. if (matrices && effect) {
  37955. effect.setMatrices("mBones", matrices);
  37956. }
  37957. }
  37958. };
  37959. /**
  37960. * Binds the morph targets information from the mesh to the effect.
  37961. * @param abstractMesh The mesh we are binding the information to render
  37962. * @param effect The effect we are binding the data to
  37963. */
  37964. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  37965. var manager = abstractMesh.morphTargetManager;
  37966. if (!abstractMesh || !manager) {
  37967. return;
  37968. }
  37969. effect.setFloatArray("morphTargetInfluences", manager.influences);
  37970. };
  37971. /**
  37972. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  37973. * @param defines The generated defines used in the effect
  37974. * @param effect The effect we are binding the data to
  37975. * @param scene The scene we are willing to render with logarithmic scale for
  37976. */
  37977. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  37978. if (defines["LOGARITHMICDEPTH"]) {
  37979. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  37980. }
  37981. };
  37982. /**
  37983. * Binds the clip plane information from the scene to the effect.
  37984. * @param scene The scene the clip plane information are extracted from
  37985. * @param effect The effect we are binding the data to
  37986. */
  37987. MaterialHelper.BindClipPlane = function (effect, scene) {
  37988. if (scene.clipPlane) {
  37989. var clipPlane = scene.clipPlane;
  37990. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  37991. }
  37992. };
  37993. return MaterialHelper;
  37994. }());
  37995. BABYLON.MaterialHelper = MaterialHelper;
  37996. })(BABYLON || (BABYLON = {}));
  37997. //# sourceMappingURL=babylon.materialHelper.js.map
  37998. var BABYLON;
  37999. (function (BABYLON) {
  38000. var PushMaterial = /** @class */ (function (_super) {
  38001. __extends(PushMaterial, _super);
  38002. function PushMaterial(name, scene) {
  38003. var _this = _super.call(this, name, scene) || this;
  38004. _this.storeEffectOnSubMeshes = true;
  38005. return _this;
  38006. }
  38007. PushMaterial.prototype.getEffect = function () {
  38008. return this._activeEffect;
  38009. };
  38010. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38011. if (!mesh) {
  38012. return false;
  38013. }
  38014. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38015. return true;
  38016. }
  38017. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38018. };
  38019. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38020. this._activeEffect.setMatrix("world", world);
  38021. };
  38022. PushMaterial.prototype.bind = function (world, mesh) {
  38023. if (!mesh) {
  38024. return;
  38025. }
  38026. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38027. };
  38028. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38029. if (effect === void 0) { effect = null; }
  38030. _super.prototype._afterBind.call(this, mesh);
  38031. this.getScene()._cachedEffect = effect;
  38032. };
  38033. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38034. if (visibility === void 0) { visibility = 1; }
  38035. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38036. };
  38037. return PushMaterial;
  38038. }(BABYLON.Material));
  38039. BABYLON.PushMaterial = PushMaterial;
  38040. })(BABYLON || (BABYLON = {}));
  38041. //# sourceMappingURL=babylon.pushMaterial.js.map
  38042. var BABYLON;
  38043. (function (BABYLON) {
  38044. /** @ignore */
  38045. var StandardMaterialDefines = /** @class */ (function (_super) {
  38046. __extends(StandardMaterialDefines, _super);
  38047. function StandardMaterialDefines() {
  38048. var _this = _super.call(this) || this;
  38049. _this.MAINUV1 = false;
  38050. _this.MAINUV2 = false;
  38051. _this.DIFFUSE = false;
  38052. _this.DIFFUSEDIRECTUV = 0;
  38053. _this.AMBIENT = false;
  38054. _this.AMBIENTDIRECTUV = 0;
  38055. _this.OPACITY = false;
  38056. _this.OPACITYDIRECTUV = 0;
  38057. _this.OPACITYRGB = false;
  38058. _this.REFLECTION = false;
  38059. _this.EMISSIVE = false;
  38060. _this.EMISSIVEDIRECTUV = 0;
  38061. _this.SPECULAR = false;
  38062. _this.SPECULARDIRECTUV = 0;
  38063. _this.BUMP = false;
  38064. _this.BUMPDIRECTUV = 0;
  38065. _this.PARALLAX = false;
  38066. _this.PARALLAXOCCLUSION = false;
  38067. _this.SPECULAROVERALPHA = false;
  38068. _this.CLIPPLANE = false;
  38069. _this.ALPHATEST = false;
  38070. _this.DEPTHPREPASS = false;
  38071. _this.ALPHAFROMDIFFUSE = false;
  38072. _this.POINTSIZE = false;
  38073. _this.FOG = false;
  38074. _this.SPECULARTERM = false;
  38075. _this.DIFFUSEFRESNEL = false;
  38076. _this.OPACITYFRESNEL = false;
  38077. _this.REFLECTIONFRESNEL = false;
  38078. _this.REFRACTIONFRESNEL = false;
  38079. _this.EMISSIVEFRESNEL = false;
  38080. _this.FRESNEL = false;
  38081. _this.NORMAL = false;
  38082. _this.UV1 = false;
  38083. _this.UV2 = false;
  38084. _this.VERTEXCOLOR = false;
  38085. _this.VERTEXALPHA = false;
  38086. _this.NUM_BONE_INFLUENCERS = 0;
  38087. _this.BonesPerMesh = 0;
  38088. _this.INSTANCES = false;
  38089. _this.GLOSSINESS = false;
  38090. _this.ROUGHNESS = false;
  38091. _this.EMISSIVEASILLUMINATION = false;
  38092. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38093. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38094. _this.LIGHTMAP = false;
  38095. _this.LIGHTMAPDIRECTUV = 0;
  38096. _this.USELIGHTMAPASSHADOWMAP = false;
  38097. _this.REFLECTIONMAP_3D = false;
  38098. _this.REFLECTIONMAP_SPHERICAL = false;
  38099. _this.REFLECTIONMAP_PLANAR = false;
  38100. _this.REFLECTIONMAP_CUBIC = false;
  38101. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38102. _this.REFLECTIONMAP_PROJECTION = false;
  38103. _this.REFLECTIONMAP_SKYBOX = false;
  38104. _this.REFLECTIONMAP_EXPLICIT = false;
  38105. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38106. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38107. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38108. _this.INVERTCUBICMAP = false;
  38109. _this.LOGARITHMICDEPTH = false;
  38110. _this.REFRACTION = false;
  38111. _this.REFRACTIONMAP_3D = false;
  38112. _this.REFLECTIONOVERALPHA = false;
  38113. _this.TWOSIDEDLIGHTING = false;
  38114. _this.SHADOWFLOAT = false;
  38115. _this.MORPHTARGETS = false;
  38116. _this.MORPHTARGETS_NORMAL = false;
  38117. _this.MORPHTARGETS_TANGENT = false;
  38118. _this.NUM_MORPH_INFLUENCERS = 0;
  38119. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38120. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38121. _this.IMAGEPROCESSING = false;
  38122. _this.VIGNETTE = false;
  38123. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38124. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38125. _this.TONEMAPPING = false;
  38126. _this.CONTRAST = false;
  38127. _this.COLORCURVES = false;
  38128. _this.COLORGRADING = false;
  38129. _this.COLORGRADING3D = false;
  38130. _this.SAMPLER3DGREENDEPTH = false;
  38131. _this.SAMPLER3DBGRMAP = false;
  38132. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38133. _this.EXPOSURE = false;
  38134. _this.rebuild();
  38135. return _this;
  38136. }
  38137. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38138. var modes = [
  38139. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38140. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38141. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38142. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38143. ];
  38144. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38145. var mode = modes_1[_i];
  38146. this[mode] = (mode === modeToEnable);
  38147. }
  38148. };
  38149. return StandardMaterialDefines;
  38150. }(BABYLON.MaterialDefines));
  38151. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38152. var StandardMaterial = /** @class */ (function (_super) {
  38153. __extends(StandardMaterial, _super);
  38154. function StandardMaterial(name, scene) {
  38155. var _this = _super.call(this, name, scene) || this;
  38156. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38157. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38158. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38159. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38160. _this.specularPower = 64;
  38161. _this._useAlphaFromDiffuseTexture = false;
  38162. _this._useEmissiveAsIllumination = false;
  38163. _this._linkEmissiveWithDiffuse = false;
  38164. _this._useSpecularOverAlpha = false;
  38165. _this._useReflectionOverAlpha = false;
  38166. _this._disableLighting = false;
  38167. _this._useParallax = false;
  38168. _this._useParallaxOcclusion = false;
  38169. _this.parallaxScaleBias = 0.05;
  38170. _this._roughness = 0;
  38171. _this.indexOfRefraction = 0.98;
  38172. _this.invertRefractionY = true;
  38173. _this._useLightmapAsShadowmap = false;
  38174. _this._useReflectionFresnelFromSpecular = false;
  38175. _this._useGlossinessFromSpecularMapAlpha = false;
  38176. _this._maxSimultaneousLights = 4;
  38177. /**
  38178. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38179. */
  38180. _this._invertNormalMapX = false;
  38181. /**
  38182. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38183. */
  38184. _this._invertNormalMapY = false;
  38185. /**
  38186. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38187. */
  38188. _this._twoSidedLighting = false;
  38189. _this._renderTargets = new BABYLON.SmartArray(16);
  38190. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38191. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38192. // Setup the default processing configuration to the scene.
  38193. _this._attachImageProcessingConfiguration(null);
  38194. _this.getRenderTargetTextures = function () {
  38195. _this._renderTargets.reset();
  38196. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38197. _this._renderTargets.push(_this._reflectionTexture);
  38198. }
  38199. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38200. _this._renderTargets.push(_this._refractionTexture);
  38201. }
  38202. return _this._renderTargets;
  38203. };
  38204. return _this;
  38205. }
  38206. ;
  38207. ;
  38208. ;
  38209. ;
  38210. ;
  38211. ;
  38212. ;
  38213. ;
  38214. ;
  38215. ;
  38216. ;
  38217. ;
  38218. ;
  38219. ;
  38220. ;
  38221. ;
  38222. ;
  38223. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38224. /**
  38225. * Gets the image processing configuration used either in this material.
  38226. */
  38227. get: function () {
  38228. return this._imageProcessingConfiguration;
  38229. },
  38230. /**
  38231. * Sets the Default image processing configuration used either in the this material.
  38232. *
  38233. * If sets to null, the scene one is in use.
  38234. */
  38235. set: function (value) {
  38236. this._attachImageProcessingConfiguration(value);
  38237. // Ensure the effect will be rebuilt.
  38238. this._markAllSubMeshesAsTexturesDirty();
  38239. },
  38240. enumerable: true,
  38241. configurable: true
  38242. });
  38243. /**
  38244. * Attaches a new image processing configuration to the Standard Material.
  38245. * @param configuration
  38246. */
  38247. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38248. var _this = this;
  38249. if (configuration === this._imageProcessingConfiguration) {
  38250. return;
  38251. }
  38252. // Detaches observer.
  38253. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38254. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38255. }
  38256. // Pick the scene configuration if needed.
  38257. if (!configuration) {
  38258. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38259. }
  38260. else {
  38261. this._imageProcessingConfiguration = configuration;
  38262. }
  38263. // Attaches observer.
  38264. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38265. _this._markAllSubMeshesAsImageProcessingDirty();
  38266. });
  38267. };
  38268. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38269. /**
  38270. * Gets wether the color curves effect is enabled.
  38271. */
  38272. get: function () {
  38273. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38274. },
  38275. /**
  38276. * Sets wether the color curves effect is enabled.
  38277. */
  38278. set: function (value) {
  38279. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38280. },
  38281. enumerable: true,
  38282. configurable: true
  38283. });
  38284. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38285. /**
  38286. * Gets wether the color grading effect is enabled.
  38287. */
  38288. get: function () {
  38289. return this.imageProcessingConfiguration.colorGradingEnabled;
  38290. },
  38291. /**
  38292. * Gets wether the color grading effect is enabled.
  38293. */
  38294. set: function (value) {
  38295. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38296. },
  38297. enumerable: true,
  38298. configurable: true
  38299. });
  38300. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38301. /**
  38302. * Gets wether tonemapping is enabled or not.
  38303. */
  38304. get: function () {
  38305. return this._imageProcessingConfiguration.toneMappingEnabled;
  38306. },
  38307. /**
  38308. * Sets wether tonemapping is enabled or not
  38309. */
  38310. set: function (value) {
  38311. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38312. },
  38313. enumerable: true,
  38314. configurable: true
  38315. });
  38316. ;
  38317. ;
  38318. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38319. /**
  38320. * The camera exposure used on this material.
  38321. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38322. * This corresponds to a photographic exposure.
  38323. */
  38324. get: function () {
  38325. return this._imageProcessingConfiguration.exposure;
  38326. },
  38327. /**
  38328. * The camera exposure used on this material.
  38329. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38330. * This corresponds to a photographic exposure.
  38331. */
  38332. set: function (value) {
  38333. this._imageProcessingConfiguration.exposure = value;
  38334. },
  38335. enumerable: true,
  38336. configurable: true
  38337. });
  38338. ;
  38339. ;
  38340. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38341. /**
  38342. * Gets The camera contrast used on this material.
  38343. */
  38344. get: function () {
  38345. return this._imageProcessingConfiguration.contrast;
  38346. },
  38347. /**
  38348. * Sets The camera contrast used on this material.
  38349. */
  38350. set: function (value) {
  38351. this._imageProcessingConfiguration.contrast = value;
  38352. },
  38353. enumerable: true,
  38354. configurable: true
  38355. });
  38356. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38357. /**
  38358. * Gets the Color Grading 2D Lookup Texture.
  38359. */
  38360. get: function () {
  38361. return this._imageProcessingConfiguration.colorGradingTexture;
  38362. },
  38363. /**
  38364. * Sets the Color Grading 2D Lookup Texture.
  38365. */
  38366. set: function (value) {
  38367. this._imageProcessingConfiguration.colorGradingTexture = value;
  38368. },
  38369. enumerable: true,
  38370. configurable: true
  38371. });
  38372. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38373. /**
  38374. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38375. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38376. * 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;
  38377. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38378. */
  38379. get: function () {
  38380. return this._imageProcessingConfiguration.colorCurves;
  38381. },
  38382. /**
  38383. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38384. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38385. * 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;
  38386. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38387. */
  38388. set: function (value) {
  38389. this._imageProcessingConfiguration.colorCurves = value;
  38390. },
  38391. enumerable: true,
  38392. configurable: true
  38393. });
  38394. StandardMaterial.prototype.getClassName = function () {
  38395. return "StandardMaterial";
  38396. };
  38397. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38398. get: function () {
  38399. return this._useLogarithmicDepth;
  38400. },
  38401. set: function (value) {
  38402. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38403. this._markAllSubMeshesAsMiscDirty();
  38404. },
  38405. enumerable: true,
  38406. configurable: true
  38407. });
  38408. StandardMaterial.prototype.needAlphaBlending = function () {
  38409. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38410. };
  38411. StandardMaterial.prototype.needAlphaTesting = function () {
  38412. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38413. };
  38414. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38415. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38416. };
  38417. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38418. return this._diffuseTexture;
  38419. };
  38420. /**
  38421. * Child classes can use it to update shaders
  38422. */
  38423. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38424. if (useInstances === void 0) { useInstances = false; }
  38425. if (subMesh.effect && this.isFrozen) {
  38426. if (this._wasPreviouslyReady && subMesh.effect) {
  38427. return true;
  38428. }
  38429. }
  38430. if (!subMesh._materialDefines) {
  38431. subMesh._materialDefines = new StandardMaterialDefines();
  38432. }
  38433. var scene = this.getScene();
  38434. var defines = subMesh._materialDefines;
  38435. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38436. if (defines._renderId === scene.getRenderId()) {
  38437. return true;
  38438. }
  38439. }
  38440. var engine = scene.getEngine();
  38441. // Lights
  38442. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38443. // Textures
  38444. if (defines._areTexturesDirty) {
  38445. defines._needUVs = false;
  38446. defines.MAINUV1 = false;
  38447. defines.MAINUV2 = false;
  38448. if (scene.texturesEnabled) {
  38449. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38450. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38451. return false;
  38452. }
  38453. else {
  38454. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38455. }
  38456. }
  38457. else {
  38458. defines.DIFFUSE = false;
  38459. }
  38460. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38461. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38462. return false;
  38463. }
  38464. else {
  38465. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38466. }
  38467. }
  38468. else {
  38469. defines.AMBIENT = false;
  38470. }
  38471. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38472. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38473. return false;
  38474. }
  38475. else {
  38476. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38477. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38478. }
  38479. }
  38480. else {
  38481. defines.OPACITY = false;
  38482. }
  38483. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38484. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38485. return false;
  38486. }
  38487. else {
  38488. defines._needNormals = true;
  38489. defines.REFLECTION = true;
  38490. defines.ROUGHNESS = (this._roughness > 0);
  38491. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38492. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38493. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38494. switch (this._reflectionTexture.coordinatesMode) {
  38495. case BABYLON.Texture.CUBIC_MODE:
  38496. case BABYLON.Texture.INVCUBIC_MODE:
  38497. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38498. break;
  38499. case BABYLON.Texture.EXPLICIT_MODE:
  38500. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38501. break;
  38502. case BABYLON.Texture.PLANAR_MODE:
  38503. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38504. break;
  38505. case BABYLON.Texture.PROJECTION_MODE:
  38506. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38507. break;
  38508. case BABYLON.Texture.SKYBOX_MODE:
  38509. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38510. break;
  38511. case BABYLON.Texture.SPHERICAL_MODE:
  38512. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38513. break;
  38514. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38515. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38516. break;
  38517. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38518. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38519. break;
  38520. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38521. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38522. break;
  38523. }
  38524. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  38525. }
  38526. }
  38527. else {
  38528. defines.REFLECTION = false;
  38529. }
  38530. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38531. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38532. return false;
  38533. }
  38534. else {
  38535. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38536. }
  38537. }
  38538. else {
  38539. defines.EMISSIVE = false;
  38540. }
  38541. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38542. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38543. return false;
  38544. }
  38545. else {
  38546. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38547. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38548. }
  38549. }
  38550. else {
  38551. defines.LIGHTMAP = false;
  38552. }
  38553. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38554. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38555. return false;
  38556. }
  38557. else {
  38558. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38559. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38560. }
  38561. }
  38562. else {
  38563. defines.SPECULAR = false;
  38564. }
  38565. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38566. // Bump texure can not be not blocking.
  38567. if (!this._bumpTexture.isReady()) {
  38568. return false;
  38569. }
  38570. else {
  38571. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38572. defines.PARALLAX = this._useParallax;
  38573. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38574. }
  38575. }
  38576. else {
  38577. defines.BUMP = false;
  38578. }
  38579. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38580. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38581. return false;
  38582. }
  38583. else {
  38584. defines._needUVs = true;
  38585. defines.REFRACTION = true;
  38586. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38587. }
  38588. }
  38589. else {
  38590. defines.REFRACTION = false;
  38591. }
  38592. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38593. }
  38594. else {
  38595. defines.DIFFUSE = false;
  38596. defines.AMBIENT = false;
  38597. defines.OPACITY = false;
  38598. defines.REFLECTION = false;
  38599. defines.EMISSIVE = false;
  38600. defines.LIGHTMAP = false;
  38601. defines.BUMP = false;
  38602. defines.REFRACTION = false;
  38603. }
  38604. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38605. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38606. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38607. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38608. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38609. }
  38610. if (defines._areImageProcessingDirty) {
  38611. if (!this._imageProcessingConfiguration.isReady()) {
  38612. return false;
  38613. }
  38614. this._imageProcessingConfiguration.prepareDefines(defines);
  38615. }
  38616. if (defines._areFresnelDirty) {
  38617. if (StandardMaterial.FresnelEnabled) {
  38618. // Fresnel
  38619. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38620. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38621. this._reflectionFresnelParameters) {
  38622. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38623. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38624. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38625. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38626. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38627. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38628. defines._needNormals = true;
  38629. defines.FRESNEL = true;
  38630. }
  38631. }
  38632. else {
  38633. defines.FRESNEL = false;
  38634. }
  38635. }
  38636. // Misc.
  38637. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  38638. // Attribs
  38639. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  38640. // Values that need to be evaluated on every frame
  38641. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  38642. // Get correct effect
  38643. if (defines.isDirty) {
  38644. defines.markAsProcessed();
  38645. scene.resetCachedMaterial();
  38646. // Fallbacks
  38647. var fallbacks = new BABYLON.EffectFallbacks();
  38648. if (defines.REFLECTION) {
  38649. fallbacks.addFallback(0, "REFLECTION");
  38650. }
  38651. if (defines.SPECULAR) {
  38652. fallbacks.addFallback(0, "SPECULAR");
  38653. }
  38654. if (defines.BUMP) {
  38655. fallbacks.addFallback(0, "BUMP");
  38656. }
  38657. if (defines.PARALLAX) {
  38658. fallbacks.addFallback(1, "PARALLAX");
  38659. }
  38660. if (defines.PARALLAXOCCLUSION) {
  38661. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38662. }
  38663. if (defines.SPECULAROVERALPHA) {
  38664. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38665. }
  38666. if (defines.FOG) {
  38667. fallbacks.addFallback(1, "FOG");
  38668. }
  38669. if (defines.POINTSIZE) {
  38670. fallbacks.addFallback(0, "POINTSIZE");
  38671. }
  38672. if (defines.LOGARITHMICDEPTH) {
  38673. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38674. }
  38675. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38676. if (defines.SPECULARTERM) {
  38677. fallbacks.addFallback(0, "SPECULARTERM");
  38678. }
  38679. if (defines.DIFFUSEFRESNEL) {
  38680. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  38681. }
  38682. if (defines.OPACITYFRESNEL) {
  38683. fallbacks.addFallback(2, "OPACITYFRESNEL");
  38684. }
  38685. if (defines.REFLECTIONFRESNEL) {
  38686. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  38687. }
  38688. if (defines.EMISSIVEFRESNEL) {
  38689. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  38690. }
  38691. if (defines.FRESNEL) {
  38692. fallbacks.addFallback(4, "FRESNEL");
  38693. }
  38694. //Attributes
  38695. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38696. if (defines.NORMAL) {
  38697. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38698. }
  38699. if (defines.UV1) {
  38700. attribs.push(BABYLON.VertexBuffer.UVKind);
  38701. }
  38702. if (defines.UV2) {
  38703. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38704. }
  38705. if (defines.VERTEXCOLOR) {
  38706. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38707. }
  38708. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38709. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38710. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38711. var shaderName = "default";
  38712. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  38713. "vFogInfos", "vFogColor", "pointSize",
  38714. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38715. "mBones",
  38716. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38717. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  38718. "vReflectionPosition", "vReflectionSize",
  38719. "logarithmicDepthConstant", "vTangentSpaceParams"
  38720. ];
  38721. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  38722. var uniformBuffers = ["Material", "Scene"];
  38723. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38724. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38725. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38726. uniformsNames: uniforms,
  38727. uniformBuffersNames: uniformBuffers,
  38728. samplers: samplers,
  38729. defines: defines,
  38730. maxSimultaneousLights: this._maxSimultaneousLights
  38731. });
  38732. if (this.customShaderNameResolve) {
  38733. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  38734. }
  38735. var join = defines.toString();
  38736. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  38737. attributes: attribs,
  38738. uniformsNames: uniforms,
  38739. uniformBuffersNames: uniformBuffers,
  38740. samplers: samplers,
  38741. defines: join,
  38742. fallbacks: fallbacks,
  38743. onCompiled: this.onCompiled,
  38744. onError: this.onError,
  38745. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38746. }, engine), defines);
  38747. this.buildUniformLayout();
  38748. }
  38749. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38750. return false;
  38751. }
  38752. defines._renderId = scene.getRenderId();
  38753. this._wasPreviouslyReady = true;
  38754. return true;
  38755. };
  38756. StandardMaterial.prototype.buildUniformLayout = function () {
  38757. // Order is important !
  38758. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  38759. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  38760. this._uniformBuffer.addUniform("opacityParts", 4);
  38761. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  38762. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  38763. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  38764. this._uniformBuffer.addUniform("refractionRightColor", 4);
  38765. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  38766. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  38767. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  38768. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  38769. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38770. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38771. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  38772. this._uniformBuffer.addUniform("vReflectionSize", 3);
  38773. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38774. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38775. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  38776. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38777. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  38778. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38779. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38780. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38781. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38782. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38783. this._uniformBuffer.addUniform("specularMatrix", 16);
  38784. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38785. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38786. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38787. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38788. this._uniformBuffer.addUniform("vSpecularColor", 4);
  38789. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38790. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  38791. this._uniformBuffer.addUniform("pointSize", 1);
  38792. this._uniformBuffer.create();
  38793. };
  38794. StandardMaterial.prototype.unbind = function () {
  38795. if (this._activeEffect) {
  38796. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38797. this._activeEffect.setTexture("reflection2DSampler", null);
  38798. }
  38799. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38800. this._activeEffect.setTexture("refraction2DSampler", null);
  38801. }
  38802. }
  38803. _super.prototype.unbind.call(this);
  38804. };
  38805. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38806. var scene = this.getScene();
  38807. var defines = subMesh._materialDefines;
  38808. if (!defines) {
  38809. return;
  38810. }
  38811. var effect = subMesh.effect;
  38812. if (!effect) {
  38813. return;
  38814. }
  38815. this._activeEffect = effect;
  38816. // Matrices
  38817. this.bindOnlyWorldMatrix(world);
  38818. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38819. // Bones
  38820. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  38821. if (mustRebind) {
  38822. this._uniformBuffer.bindToEffect(effect, "Material");
  38823. this.bindViewProjection(effect);
  38824. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38825. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  38826. // Fresnel
  38827. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  38828. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  38829. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  38830. }
  38831. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  38832. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  38833. }
  38834. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  38835. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  38836. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  38837. }
  38838. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  38839. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  38840. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  38841. }
  38842. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  38843. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  38844. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  38845. }
  38846. }
  38847. // Textures
  38848. if (scene.texturesEnabled) {
  38849. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38850. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  38851. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  38852. }
  38853. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38854. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  38855. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38856. }
  38857. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38858. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38859. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38860. }
  38861. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38862. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  38863. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  38864. if (this._reflectionTexture.boundingBoxSize) {
  38865. var cubeTexture = this._reflectionTexture;
  38866. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  38867. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  38868. }
  38869. }
  38870. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38871. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38872. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38873. }
  38874. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38875. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38876. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38877. }
  38878. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38879. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  38880. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  38881. }
  38882. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  38883. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  38884. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38885. if (scene._mirroredCameraPosition) {
  38886. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38887. }
  38888. else {
  38889. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38890. }
  38891. }
  38892. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38893. var depth = 1.0;
  38894. if (!this._refractionTexture.isCube) {
  38895. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  38896. if (this._refractionTexture.depth) {
  38897. depth = this._refractionTexture.depth;
  38898. }
  38899. }
  38900. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  38901. }
  38902. }
  38903. // Point size
  38904. if (this.pointsCloud) {
  38905. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  38906. }
  38907. if (defines.SPECULARTERM) {
  38908. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  38909. }
  38910. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  38911. // Diffuse
  38912. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  38913. }
  38914. // Textures
  38915. if (scene.texturesEnabled) {
  38916. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38917. effect.setTexture("diffuseSampler", this._diffuseTexture);
  38918. }
  38919. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38920. effect.setTexture("ambientSampler", this._ambientTexture);
  38921. }
  38922. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38923. effect.setTexture("opacitySampler", this._opacityTexture);
  38924. }
  38925. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38926. if (this._reflectionTexture.isCube) {
  38927. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  38928. }
  38929. else {
  38930. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  38931. }
  38932. }
  38933. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38934. effect.setTexture("emissiveSampler", this._emissiveTexture);
  38935. }
  38936. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38937. effect.setTexture("lightmapSampler", this._lightmapTexture);
  38938. }
  38939. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38940. effect.setTexture("specularSampler", this._specularTexture);
  38941. }
  38942. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  38943. effect.setTexture("bumpSampler", this._bumpTexture);
  38944. }
  38945. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38946. var depth = 1.0;
  38947. if (this._refractionTexture.isCube) {
  38948. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  38949. }
  38950. else {
  38951. effect.setTexture("refraction2DSampler", this._refractionTexture);
  38952. }
  38953. }
  38954. }
  38955. // Clip plane
  38956. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  38957. // Colors
  38958. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  38959. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  38960. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  38961. }
  38962. if (mustRebind || !this.isFrozen) {
  38963. // Lights
  38964. if (scene.lightsEnabled && !this._disableLighting) {
  38965. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  38966. }
  38967. // View
  38968. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  38969. this.bindView(effect);
  38970. }
  38971. // Fog
  38972. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  38973. // Morph targets
  38974. if (defines.NUM_MORPH_INFLUENCERS) {
  38975. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  38976. }
  38977. // Log. depth
  38978. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  38979. // image processing
  38980. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  38981. this._imageProcessingConfiguration.bind(this._activeEffect);
  38982. }
  38983. }
  38984. this._uniformBuffer.update();
  38985. this._afterBind(mesh, this._activeEffect);
  38986. };
  38987. StandardMaterial.prototype.getAnimatables = function () {
  38988. var results = [];
  38989. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  38990. results.push(this._diffuseTexture);
  38991. }
  38992. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  38993. results.push(this._ambientTexture);
  38994. }
  38995. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  38996. results.push(this._opacityTexture);
  38997. }
  38998. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  38999. results.push(this._reflectionTexture);
  39000. }
  39001. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39002. results.push(this._emissiveTexture);
  39003. }
  39004. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39005. results.push(this._specularTexture);
  39006. }
  39007. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39008. results.push(this._bumpTexture);
  39009. }
  39010. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39011. results.push(this._lightmapTexture);
  39012. }
  39013. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39014. results.push(this._refractionTexture);
  39015. }
  39016. return results;
  39017. };
  39018. StandardMaterial.prototype.getActiveTextures = function () {
  39019. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39020. if (this._diffuseTexture) {
  39021. activeTextures.push(this._diffuseTexture);
  39022. }
  39023. if (this._ambientTexture) {
  39024. activeTextures.push(this._ambientTexture);
  39025. }
  39026. if (this._opacityTexture) {
  39027. activeTextures.push(this._opacityTexture);
  39028. }
  39029. if (this._reflectionTexture) {
  39030. activeTextures.push(this._reflectionTexture);
  39031. }
  39032. if (this._emissiveTexture) {
  39033. activeTextures.push(this._emissiveTexture);
  39034. }
  39035. if (this._specularTexture) {
  39036. activeTextures.push(this._specularTexture);
  39037. }
  39038. if (this._bumpTexture) {
  39039. activeTextures.push(this._bumpTexture);
  39040. }
  39041. if (this._lightmapTexture) {
  39042. activeTextures.push(this._lightmapTexture);
  39043. }
  39044. if (this._refractionTexture) {
  39045. activeTextures.push(this._refractionTexture);
  39046. }
  39047. return activeTextures;
  39048. };
  39049. StandardMaterial.prototype.hasTexture = function (texture) {
  39050. if (_super.prototype.hasTexture.call(this, texture)) {
  39051. return true;
  39052. }
  39053. if (this._diffuseTexture === texture) {
  39054. return true;
  39055. }
  39056. if (this._ambientTexture === texture) {
  39057. return true;
  39058. }
  39059. if (this._opacityTexture === texture) {
  39060. return true;
  39061. }
  39062. if (this._reflectionTexture === texture) {
  39063. return true;
  39064. }
  39065. if (this._emissiveTexture === texture) {
  39066. return true;
  39067. }
  39068. if (this._specularTexture === texture) {
  39069. return true;
  39070. }
  39071. if (this._bumpTexture === texture) {
  39072. return true;
  39073. }
  39074. if (this._lightmapTexture === texture) {
  39075. return true;
  39076. }
  39077. if (this._refractionTexture === texture) {
  39078. return true;
  39079. }
  39080. return false;
  39081. };
  39082. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39083. if (forceDisposeTextures) {
  39084. if (this._diffuseTexture) {
  39085. this._diffuseTexture.dispose();
  39086. }
  39087. if (this._ambientTexture) {
  39088. this._ambientTexture.dispose();
  39089. }
  39090. if (this._opacityTexture) {
  39091. this._opacityTexture.dispose();
  39092. }
  39093. if (this._reflectionTexture) {
  39094. this._reflectionTexture.dispose();
  39095. }
  39096. if (this._emissiveTexture) {
  39097. this._emissiveTexture.dispose();
  39098. }
  39099. if (this._specularTexture) {
  39100. this._specularTexture.dispose();
  39101. }
  39102. if (this._bumpTexture) {
  39103. this._bumpTexture.dispose();
  39104. }
  39105. if (this._lightmapTexture) {
  39106. this._lightmapTexture.dispose();
  39107. }
  39108. if (this._refractionTexture) {
  39109. this._refractionTexture.dispose();
  39110. }
  39111. }
  39112. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39113. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39114. }
  39115. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39116. };
  39117. StandardMaterial.prototype.clone = function (name) {
  39118. var _this = this;
  39119. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39120. result.name = name;
  39121. result.id = name;
  39122. return result;
  39123. };
  39124. StandardMaterial.prototype.serialize = function () {
  39125. return BABYLON.SerializationHelper.Serialize(this);
  39126. };
  39127. // Statics
  39128. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39129. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39130. };
  39131. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39132. get: function () {
  39133. return StandardMaterial._DiffuseTextureEnabled;
  39134. },
  39135. set: function (value) {
  39136. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39137. return;
  39138. }
  39139. StandardMaterial._DiffuseTextureEnabled = value;
  39140. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39141. },
  39142. enumerable: true,
  39143. configurable: true
  39144. });
  39145. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39146. get: function () {
  39147. return StandardMaterial._AmbientTextureEnabled;
  39148. },
  39149. set: function (value) {
  39150. if (StandardMaterial._AmbientTextureEnabled === value) {
  39151. return;
  39152. }
  39153. StandardMaterial._AmbientTextureEnabled = value;
  39154. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39155. },
  39156. enumerable: true,
  39157. configurable: true
  39158. });
  39159. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39160. get: function () {
  39161. return StandardMaterial._OpacityTextureEnabled;
  39162. },
  39163. set: function (value) {
  39164. if (StandardMaterial._OpacityTextureEnabled === value) {
  39165. return;
  39166. }
  39167. StandardMaterial._OpacityTextureEnabled = value;
  39168. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39169. },
  39170. enumerable: true,
  39171. configurable: true
  39172. });
  39173. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39174. get: function () {
  39175. return StandardMaterial._ReflectionTextureEnabled;
  39176. },
  39177. set: function (value) {
  39178. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39179. return;
  39180. }
  39181. StandardMaterial._ReflectionTextureEnabled = value;
  39182. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39183. },
  39184. enumerable: true,
  39185. configurable: true
  39186. });
  39187. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39188. get: function () {
  39189. return StandardMaterial._EmissiveTextureEnabled;
  39190. },
  39191. set: function (value) {
  39192. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39193. return;
  39194. }
  39195. StandardMaterial._EmissiveTextureEnabled = value;
  39196. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39197. },
  39198. enumerable: true,
  39199. configurable: true
  39200. });
  39201. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39202. get: function () {
  39203. return StandardMaterial._SpecularTextureEnabled;
  39204. },
  39205. set: function (value) {
  39206. if (StandardMaterial._SpecularTextureEnabled === value) {
  39207. return;
  39208. }
  39209. StandardMaterial._SpecularTextureEnabled = value;
  39210. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39211. },
  39212. enumerable: true,
  39213. configurable: true
  39214. });
  39215. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39216. get: function () {
  39217. return StandardMaterial._BumpTextureEnabled;
  39218. },
  39219. set: function (value) {
  39220. if (StandardMaterial._BumpTextureEnabled === value) {
  39221. return;
  39222. }
  39223. StandardMaterial._BumpTextureEnabled = value;
  39224. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39225. },
  39226. enumerable: true,
  39227. configurable: true
  39228. });
  39229. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39230. get: function () {
  39231. return StandardMaterial._LightmapTextureEnabled;
  39232. },
  39233. set: function (value) {
  39234. if (StandardMaterial._LightmapTextureEnabled === value) {
  39235. return;
  39236. }
  39237. StandardMaterial._LightmapTextureEnabled = value;
  39238. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39239. },
  39240. enumerable: true,
  39241. configurable: true
  39242. });
  39243. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39244. get: function () {
  39245. return StandardMaterial._RefractionTextureEnabled;
  39246. },
  39247. set: function (value) {
  39248. if (StandardMaterial._RefractionTextureEnabled === value) {
  39249. return;
  39250. }
  39251. StandardMaterial._RefractionTextureEnabled = value;
  39252. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39253. },
  39254. enumerable: true,
  39255. configurable: true
  39256. });
  39257. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39258. get: function () {
  39259. return StandardMaterial._ColorGradingTextureEnabled;
  39260. },
  39261. set: function (value) {
  39262. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39263. return;
  39264. }
  39265. StandardMaterial._ColorGradingTextureEnabled = value;
  39266. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39267. },
  39268. enumerable: true,
  39269. configurable: true
  39270. });
  39271. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39272. get: function () {
  39273. return StandardMaterial._FresnelEnabled;
  39274. },
  39275. set: function (value) {
  39276. if (StandardMaterial._FresnelEnabled === value) {
  39277. return;
  39278. }
  39279. StandardMaterial._FresnelEnabled = value;
  39280. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39281. },
  39282. enumerable: true,
  39283. configurable: true
  39284. });
  39285. // Flags used to enable or disable a type of texture for all Standard Materials
  39286. StandardMaterial._DiffuseTextureEnabled = true;
  39287. StandardMaterial._AmbientTextureEnabled = true;
  39288. StandardMaterial._OpacityTextureEnabled = true;
  39289. StandardMaterial._ReflectionTextureEnabled = true;
  39290. StandardMaterial._EmissiveTextureEnabled = true;
  39291. StandardMaterial._SpecularTextureEnabled = true;
  39292. StandardMaterial._BumpTextureEnabled = true;
  39293. StandardMaterial._LightmapTextureEnabled = true;
  39294. StandardMaterial._RefractionTextureEnabled = true;
  39295. StandardMaterial._ColorGradingTextureEnabled = true;
  39296. StandardMaterial._FresnelEnabled = true;
  39297. __decorate([
  39298. BABYLON.serializeAsTexture("diffuseTexture")
  39299. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39300. __decorate([
  39301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39302. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39303. __decorate([
  39304. BABYLON.serializeAsTexture("ambientTexture")
  39305. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39306. __decorate([
  39307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39308. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39309. __decorate([
  39310. BABYLON.serializeAsTexture("opacityTexture")
  39311. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39312. __decorate([
  39313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39314. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39315. __decorate([
  39316. BABYLON.serializeAsTexture("reflectionTexture")
  39317. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39318. __decorate([
  39319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39320. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39321. __decorate([
  39322. BABYLON.serializeAsTexture("emissiveTexture")
  39323. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39324. __decorate([
  39325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39326. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39327. __decorate([
  39328. BABYLON.serializeAsTexture("specularTexture")
  39329. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39330. __decorate([
  39331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39332. ], StandardMaterial.prototype, "specularTexture", void 0);
  39333. __decorate([
  39334. BABYLON.serializeAsTexture("bumpTexture")
  39335. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39336. __decorate([
  39337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39338. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39339. __decorate([
  39340. BABYLON.serializeAsTexture("lightmapTexture")
  39341. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39342. __decorate([
  39343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39344. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39345. __decorate([
  39346. BABYLON.serializeAsTexture("refractionTexture")
  39347. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39348. __decorate([
  39349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39350. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39351. __decorate([
  39352. BABYLON.serializeAsColor3("ambient")
  39353. ], StandardMaterial.prototype, "ambientColor", void 0);
  39354. __decorate([
  39355. BABYLON.serializeAsColor3("diffuse")
  39356. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39357. __decorate([
  39358. BABYLON.serializeAsColor3("specular")
  39359. ], StandardMaterial.prototype, "specularColor", void 0);
  39360. __decorate([
  39361. BABYLON.serializeAsColor3("emissive")
  39362. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39363. __decorate([
  39364. BABYLON.serialize()
  39365. ], StandardMaterial.prototype, "specularPower", void 0);
  39366. __decorate([
  39367. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39368. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39369. __decorate([
  39370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39371. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39372. __decorate([
  39373. BABYLON.serialize("useEmissiveAsIllumination")
  39374. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39375. __decorate([
  39376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39377. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39378. __decorate([
  39379. BABYLON.serialize("linkEmissiveWithDiffuse")
  39380. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39381. __decorate([
  39382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39383. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39384. __decorate([
  39385. BABYLON.serialize("useSpecularOverAlpha")
  39386. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39387. __decorate([
  39388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39389. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39390. __decorate([
  39391. BABYLON.serialize("useReflectionOverAlpha")
  39392. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39393. __decorate([
  39394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39395. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39396. __decorate([
  39397. BABYLON.serialize("disableLighting")
  39398. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39399. __decorate([
  39400. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39401. ], StandardMaterial.prototype, "disableLighting", void 0);
  39402. __decorate([
  39403. BABYLON.serialize("useParallax")
  39404. ], StandardMaterial.prototype, "_useParallax", void 0);
  39405. __decorate([
  39406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39407. ], StandardMaterial.prototype, "useParallax", void 0);
  39408. __decorate([
  39409. BABYLON.serialize("useParallaxOcclusion")
  39410. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39411. __decorate([
  39412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39413. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39414. __decorate([
  39415. BABYLON.serialize()
  39416. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39417. __decorate([
  39418. BABYLON.serialize("roughness")
  39419. ], StandardMaterial.prototype, "_roughness", void 0);
  39420. __decorate([
  39421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39422. ], StandardMaterial.prototype, "roughness", void 0);
  39423. __decorate([
  39424. BABYLON.serialize()
  39425. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39426. __decorate([
  39427. BABYLON.serialize()
  39428. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39429. __decorate([
  39430. BABYLON.serialize("useLightmapAsShadowmap")
  39431. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39432. __decorate([
  39433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39434. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39435. __decorate([
  39436. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39437. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39438. __decorate([
  39439. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39440. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39441. __decorate([
  39442. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39443. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39444. __decorate([
  39445. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39446. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39447. __decorate([
  39448. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39449. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39450. __decorate([
  39451. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39452. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39453. __decorate([
  39454. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39455. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39456. __decorate([
  39457. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39458. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39459. __decorate([
  39460. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39461. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39462. __decorate([
  39463. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39464. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39465. __decorate([
  39466. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39467. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39468. __decorate([
  39469. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39470. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39471. __decorate([
  39472. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39473. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39474. __decorate([
  39475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39476. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39477. __decorate([
  39478. BABYLON.serialize("maxSimultaneousLights")
  39479. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39480. __decorate([
  39481. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39482. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39483. __decorate([
  39484. BABYLON.serialize("invertNormalMapX")
  39485. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39486. __decorate([
  39487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39488. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39489. __decorate([
  39490. BABYLON.serialize("invertNormalMapY")
  39491. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39492. __decorate([
  39493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39494. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39495. __decorate([
  39496. BABYLON.serialize("twoSidedLighting")
  39497. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39498. __decorate([
  39499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39500. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39501. __decorate([
  39502. BABYLON.serialize()
  39503. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39504. return StandardMaterial;
  39505. }(BABYLON.PushMaterial));
  39506. BABYLON.StandardMaterial = StandardMaterial;
  39507. })(BABYLON || (BABYLON = {}));
  39508. //# sourceMappingURL=babylon.standardMaterial.js.map
  39509. var __assign = (this && this.__assign) || Object.assign || function(t) {
  39510. for (var s, i = 1, n = arguments.length; i < n; i++) {
  39511. s = arguments[i];
  39512. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  39513. t[p] = s[p];
  39514. }
  39515. return t;
  39516. };
  39517. var BABYLON;
  39518. (function (BABYLON) {
  39519. /**
  39520. * Manages the defines for the PBR Material.
  39521. */
  39522. var PBRMaterialDefines = /** @class */ (function (_super) {
  39523. __extends(PBRMaterialDefines, _super);
  39524. /**
  39525. * Initializes the PBR Material defines.
  39526. */
  39527. function PBRMaterialDefines() {
  39528. var _this = _super.call(this) || this;
  39529. _this.PBR = true;
  39530. _this.MAINUV1 = false;
  39531. _this.MAINUV2 = false;
  39532. _this.UV1 = false;
  39533. _this.UV2 = false;
  39534. _this.ALBEDO = false;
  39535. _this.ALBEDODIRECTUV = 0;
  39536. _this.VERTEXCOLOR = false;
  39537. _this.AMBIENT = false;
  39538. _this.AMBIENTDIRECTUV = 0;
  39539. _this.AMBIENTINGRAYSCALE = false;
  39540. _this.OPACITY = false;
  39541. _this.VERTEXALPHA = false;
  39542. _this.OPACITYDIRECTUV = 0;
  39543. _this.OPACITYRGB = false;
  39544. _this.ALPHATEST = false;
  39545. _this.DEPTHPREPASS = false;
  39546. _this.ALPHABLEND = false;
  39547. _this.ALPHAFROMALBEDO = false;
  39548. _this.ALPHATESTVALUE = 0.5;
  39549. _this.SPECULAROVERALPHA = false;
  39550. _this.RADIANCEOVERALPHA = false;
  39551. _this.ALPHAFRESNEL = false;
  39552. _this.LINEARALPHAFRESNEL = false;
  39553. _this.PREMULTIPLYALPHA = false;
  39554. _this.EMISSIVE = false;
  39555. _this.EMISSIVEDIRECTUV = 0;
  39556. _this.REFLECTIVITY = false;
  39557. _this.REFLECTIVITYDIRECTUV = 0;
  39558. _this.SPECULARTERM = false;
  39559. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39560. _this.MICROSURFACEAUTOMATIC = false;
  39561. _this.LODBASEDMICROSFURACE = false;
  39562. _this.MICROSURFACEMAP = false;
  39563. _this.MICROSURFACEMAPDIRECTUV = 0;
  39564. _this.METALLICWORKFLOW = false;
  39565. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39566. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39567. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39568. _this.AOSTOREINMETALMAPRED = false;
  39569. _this.ENVIRONMENTBRDF = false;
  39570. _this.NORMAL = false;
  39571. _this.TANGENT = false;
  39572. _this.BUMP = false;
  39573. _this.BUMPDIRECTUV = 0;
  39574. _this.PARALLAX = false;
  39575. _this.PARALLAXOCCLUSION = false;
  39576. _this.NORMALXYSCALE = true;
  39577. _this.LIGHTMAP = false;
  39578. _this.LIGHTMAPDIRECTUV = 0;
  39579. _this.USELIGHTMAPASSHADOWMAP = false;
  39580. _this.REFLECTION = false;
  39581. _this.REFLECTIONMAP_3D = false;
  39582. _this.REFLECTIONMAP_SPHERICAL = false;
  39583. _this.REFLECTIONMAP_PLANAR = false;
  39584. _this.REFLECTIONMAP_CUBIC = false;
  39585. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39586. _this.REFLECTIONMAP_PROJECTION = false;
  39587. _this.REFLECTIONMAP_SKYBOX = false;
  39588. _this.REFLECTIONMAP_EXPLICIT = false;
  39589. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39590. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39591. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39592. _this.INVERTCUBICMAP = false;
  39593. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39594. _this.USESPHERICALINVERTEX = false;
  39595. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39596. _this.LODINREFLECTIONALPHA = false;
  39597. _this.GAMMAREFLECTION = false;
  39598. _this.RADIANCEOCCLUSION = false;
  39599. _this.HORIZONOCCLUSION = false;
  39600. _this.REFRACTION = false;
  39601. _this.REFRACTIONMAP_3D = false;
  39602. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39603. _this.LODINREFRACTIONALPHA = false;
  39604. _this.GAMMAREFRACTION = false;
  39605. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39606. _this.INSTANCES = false;
  39607. _this.NUM_BONE_INFLUENCERS = 0;
  39608. _this.BonesPerMesh = 0;
  39609. _this.NONUNIFORMSCALING = false;
  39610. _this.MORPHTARGETS = false;
  39611. _this.MORPHTARGETS_NORMAL = false;
  39612. _this.MORPHTARGETS_TANGENT = false;
  39613. _this.NUM_MORPH_INFLUENCERS = 0;
  39614. _this.IMAGEPROCESSING = false;
  39615. _this.VIGNETTE = false;
  39616. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39617. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39618. _this.TONEMAPPING = false;
  39619. _this.CONTRAST = false;
  39620. _this.COLORCURVES = false;
  39621. _this.COLORGRADING = false;
  39622. _this.COLORGRADING3D = false;
  39623. _this.SAMPLER3DGREENDEPTH = false;
  39624. _this.SAMPLER3DBGRMAP = false;
  39625. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39626. _this.EXPOSURE = false;
  39627. _this.USEPHYSICALLIGHTFALLOFF = false;
  39628. _this.TWOSIDEDLIGHTING = false;
  39629. _this.SHADOWFLOAT = false;
  39630. _this.CLIPPLANE = false;
  39631. _this.POINTSIZE = false;
  39632. _this.FOG = false;
  39633. _this.LOGARITHMICDEPTH = false;
  39634. _this.FORCENORMALFORWARD = false;
  39635. _this.rebuild();
  39636. return _this;
  39637. }
  39638. /**
  39639. * Resets the PBR Material defines.
  39640. */
  39641. PBRMaterialDefines.prototype.reset = function () {
  39642. _super.prototype.reset.call(this);
  39643. this.ALPHATESTVALUE = 0.5;
  39644. this.PBR = true;
  39645. };
  39646. return PBRMaterialDefines;
  39647. }(BABYLON.MaterialDefines));
  39648. /**
  39649. * The Physically based material base class of BJS.
  39650. *
  39651. * This offers the main features of a standard PBR material.
  39652. * For more information, please refer to the documentation :
  39653. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39654. */
  39655. var PBRBaseMaterial = /** @class */ (function (_super) {
  39656. __extends(PBRBaseMaterial, _super);
  39657. /**
  39658. * Instantiates a new PBRMaterial instance.
  39659. *
  39660. * @param name The material name
  39661. * @param scene The scene the material will be use in.
  39662. */
  39663. function PBRBaseMaterial(name, scene) {
  39664. var _this = _super.call(this, name, scene) || this;
  39665. /**
  39666. * Intensity of the direct lights e.g. the four lights available in your scene.
  39667. * This impacts both the direct diffuse and specular highlights.
  39668. */
  39669. _this._directIntensity = 1.0;
  39670. /**
  39671. * Intensity of the emissive part of the material.
  39672. * This helps controlling the emissive effect without modifying the emissive color.
  39673. */
  39674. _this._emissiveIntensity = 1.0;
  39675. /**
  39676. * Intensity of the environment e.g. how much the environment will light the object
  39677. * either through harmonics for rough material or through the refelction for shiny ones.
  39678. */
  39679. _this._environmentIntensity = 1.0;
  39680. /**
  39681. * This is a special control allowing the reduction of the specular highlights coming from the
  39682. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39683. */
  39684. _this._specularIntensity = 1.0;
  39685. /**
  39686. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  39687. */
  39688. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  39689. /**
  39690. * Debug Control allowing disabling the bump map on this material.
  39691. */
  39692. _this._disableBumpMap = false;
  39693. /**
  39694. * AKA Occlusion Texture Intensity in other nomenclature.
  39695. */
  39696. _this._ambientTextureStrength = 1.0;
  39697. /**
  39698. * The color of a material in ambient lighting.
  39699. */
  39700. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  39701. /**
  39702. * AKA Diffuse Color in other nomenclature.
  39703. */
  39704. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  39705. /**
  39706. * AKA Specular Color in other nomenclature.
  39707. */
  39708. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39709. /**
  39710. * The color applied when light is reflected from a material.
  39711. */
  39712. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  39713. /**
  39714. * The color applied when light is emitted from a material.
  39715. */
  39716. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  39717. /**
  39718. * AKA Glossiness in other nomenclature.
  39719. */
  39720. _this._microSurface = 0.9;
  39721. /**
  39722. * source material index of refraction (IOR)' / 'destination material IOR.
  39723. */
  39724. _this._indexOfRefraction = 0.66;
  39725. /**
  39726. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39727. */
  39728. _this._invertRefractionY = false;
  39729. /**
  39730. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39731. * Materials half opaque for instance using refraction could benefit from this control.
  39732. */
  39733. _this._linkRefractionWithTransparency = false;
  39734. /**
  39735. * Specifies that the material will use the light map as a show map.
  39736. */
  39737. _this._useLightmapAsShadowmap = false;
  39738. /**
  39739. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39740. * makes the reflect vector face the model (under horizon).
  39741. */
  39742. _this._useHorizonOcclusion = true;
  39743. /**
  39744. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39745. * too much the area relying on ambient texture to define their ambient occlusion.
  39746. */
  39747. _this._useRadianceOcclusion = true;
  39748. /**
  39749. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39750. */
  39751. _this._useAlphaFromAlbedoTexture = false;
  39752. /**
  39753. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39754. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39755. */
  39756. _this._useSpecularOverAlpha = true;
  39757. /**
  39758. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39759. */
  39760. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  39761. /**
  39762. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39763. */
  39764. _this._useRoughnessFromMetallicTextureAlpha = true;
  39765. /**
  39766. * Specifies if the metallic texture contains the roughness information in its green channel.
  39767. */
  39768. _this._useRoughnessFromMetallicTextureGreen = false;
  39769. /**
  39770. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39771. */
  39772. _this._useMetallnessFromMetallicTextureBlue = false;
  39773. /**
  39774. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39775. */
  39776. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  39777. /**
  39778. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39779. */
  39780. _this._useAmbientInGrayScale = false;
  39781. /**
  39782. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39783. * The material will try to infer what glossiness each pixel should be.
  39784. */
  39785. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  39786. /**
  39787. * BJS is using an harcoded light falloff based on a manually sets up range.
  39788. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39789. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39790. */
  39791. _this._usePhysicalLightFalloff = true;
  39792. /**
  39793. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39794. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39795. */
  39796. _this._useRadianceOverAlpha = true;
  39797. /**
  39798. * Allows using the bump map in parallax mode.
  39799. */
  39800. _this._useParallax = false;
  39801. /**
  39802. * Allows using the bump map in parallax occlusion mode.
  39803. */
  39804. _this._useParallaxOcclusion = false;
  39805. /**
  39806. * Controls the scale bias of the parallax mode.
  39807. */
  39808. _this._parallaxScaleBias = 0.05;
  39809. /**
  39810. * If sets to true, disables all the lights affecting the material.
  39811. */
  39812. _this._disableLighting = false;
  39813. /**
  39814. * Number of Simultaneous lights allowed on the material.
  39815. */
  39816. _this._maxSimultaneousLights = 4;
  39817. /**
  39818. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  39819. */
  39820. _this._invertNormalMapX = false;
  39821. /**
  39822. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  39823. */
  39824. _this._invertNormalMapY = false;
  39825. /**
  39826. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39827. */
  39828. _this._twoSidedLighting = false;
  39829. /**
  39830. * Defines the alpha limits in alpha test mode.
  39831. */
  39832. _this._alphaCutOff = 0.4;
  39833. /**
  39834. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39835. */
  39836. _this._forceAlphaTest = false;
  39837. /**
  39838. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39839. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39840. */
  39841. _this._useAlphaFresnel = false;
  39842. /**
  39843. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39844. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39845. */
  39846. _this._useLinearAlphaFresnel = false;
  39847. /**
  39848. * The transparency mode of the material.
  39849. */
  39850. _this._transparencyMode = null;
  39851. /**
  39852. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  39853. * from cos thetav and roughness:
  39854. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  39855. */
  39856. _this._environmentBRDFTexture = null;
  39857. /**
  39858. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39859. */
  39860. _this._forceIrradianceInFragment = false;
  39861. /**
  39862. * Force normal to face away from face.
  39863. */
  39864. _this._forceNormalForward = false;
  39865. /**
  39866. * Force metallic workflow.
  39867. */
  39868. _this._forceMetallicWorkflow = false;
  39869. /**
  39870. * Stores the available render targets.
  39871. */
  39872. _this._renderTargets = new BABYLON.SmartArray(16);
  39873. /**
  39874. * Sets the global ambient color for the material used in lighting calculations.
  39875. */
  39876. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39877. // Setup the default processing configuration to the scene.
  39878. _this._attachImageProcessingConfiguration(null);
  39879. _this.getRenderTargetTextures = function () {
  39880. _this._renderTargets.reset();
  39881. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39882. _this._renderTargets.push(_this._reflectionTexture);
  39883. }
  39884. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39885. _this._renderTargets.push(_this._refractionTexture);
  39886. }
  39887. return _this._renderTargets;
  39888. };
  39889. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39890. return _this;
  39891. }
  39892. /**
  39893. * Attaches a new image processing configuration to the PBR Material.
  39894. * @param configuration
  39895. */
  39896. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39897. var _this = this;
  39898. if (configuration === this._imageProcessingConfiguration) {
  39899. return;
  39900. }
  39901. // Detaches observer.
  39902. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39903. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39904. }
  39905. // Pick the scene configuration if needed.
  39906. if (!configuration) {
  39907. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39908. }
  39909. else {
  39910. this._imageProcessingConfiguration = configuration;
  39911. }
  39912. // Attaches observer.
  39913. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39914. _this._markAllSubMeshesAsImageProcessingDirty();
  39915. });
  39916. };
  39917. /**
  39918. * Gets the name of the material class.
  39919. */
  39920. PBRBaseMaterial.prototype.getClassName = function () {
  39921. return "PBRBaseMaterial";
  39922. };
  39923. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  39924. /**
  39925. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  39926. */
  39927. get: function () {
  39928. return this._useLogarithmicDepth;
  39929. },
  39930. /**
  39931. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  39932. */
  39933. set: function (value) {
  39934. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39935. },
  39936. enumerable: true,
  39937. configurable: true
  39938. });
  39939. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  39940. /**
  39941. * Gets the current transparency mode.
  39942. */
  39943. get: function () {
  39944. return this._transparencyMode;
  39945. },
  39946. /**
  39947. * Sets the transparency mode of the material.
  39948. */
  39949. set: function (value) {
  39950. if (this._transparencyMode === value) {
  39951. return;
  39952. }
  39953. this._transparencyMode = value;
  39954. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  39955. this._markAllSubMeshesAsTexturesAndMiscDirty();
  39956. },
  39957. enumerable: true,
  39958. configurable: true
  39959. });
  39960. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  39961. /**
  39962. * Returns true if alpha blending should be disabled.
  39963. */
  39964. get: function () {
  39965. return (this._linkRefractionWithTransparency ||
  39966. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  39967. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  39968. },
  39969. enumerable: true,
  39970. configurable: true
  39971. });
  39972. /**
  39973. * Specifies whether or not this material should be rendered in alpha blend mode.
  39974. */
  39975. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  39976. if (this._disableAlphaBlending) {
  39977. return false;
  39978. }
  39979. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  39980. };
  39981. /**
  39982. * Specifies if the mesh will require alpha blending.
  39983. * @param mesh - BJS mesh.
  39984. */
  39985. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  39986. if (this._disableAlphaBlending) {
  39987. return false;
  39988. }
  39989. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  39990. };
  39991. /**
  39992. * Specifies whether or not this material should be rendered in alpha test mode.
  39993. */
  39994. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  39995. if (this._forceAlphaTest) {
  39996. return true;
  39997. }
  39998. if (this._linkRefractionWithTransparency) {
  39999. return false;
  40000. }
  40001. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40002. };
  40003. /**
  40004. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40005. */
  40006. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40007. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40008. };
  40009. /**
  40010. * Gets the texture used for the alpha test.
  40011. */
  40012. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40013. return this._albedoTexture;
  40014. };
  40015. /**
  40016. * Specifies that the submesh is ready to be used.
  40017. * @param mesh - BJS mesh.
  40018. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40019. * @param useInstances - Specifies that instances should be used.
  40020. * @returns - boolean indicating that the submesh is ready or not.
  40021. */
  40022. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40023. if (subMesh.effect && this.isFrozen) {
  40024. if (this._wasPreviouslyReady) {
  40025. return true;
  40026. }
  40027. }
  40028. if (!subMesh._materialDefines) {
  40029. subMesh._materialDefines = new PBRMaterialDefines();
  40030. }
  40031. var defines = subMesh._materialDefines;
  40032. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40033. if (defines._renderId === this.getScene().getRenderId()) {
  40034. return true;
  40035. }
  40036. }
  40037. var scene = this.getScene();
  40038. var engine = scene.getEngine();
  40039. if (defines._areTexturesDirty) {
  40040. if (scene.texturesEnabled) {
  40041. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40042. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40043. return false;
  40044. }
  40045. }
  40046. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40047. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40048. return false;
  40049. }
  40050. }
  40051. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40052. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40053. return false;
  40054. }
  40055. }
  40056. var reflectionTexture = this._getReflectionTexture();
  40057. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40058. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40059. return false;
  40060. }
  40061. }
  40062. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40063. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40064. return false;
  40065. }
  40066. }
  40067. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40068. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40069. return false;
  40070. }
  40071. }
  40072. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40073. if (this._metallicTexture) {
  40074. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40075. return false;
  40076. }
  40077. }
  40078. else if (this._reflectivityTexture) {
  40079. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40080. return false;
  40081. }
  40082. }
  40083. if (this._microSurfaceTexture) {
  40084. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40085. return false;
  40086. }
  40087. }
  40088. }
  40089. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40090. // Bump texture cannot be not blocking.
  40091. if (!this._bumpTexture.isReady()) {
  40092. return false;
  40093. }
  40094. }
  40095. var refractionTexture = this._getRefractionTexture();
  40096. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40097. if (!refractionTexture.isReadyOrNotBlocking()) {
  40098. return false;
  40099. }
  40100. }
  40101. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40102. // This is blocking.
  40103. if (!this._environmentBRDFTexture.isReady()) {
  40104. return false;
  40105. }
  40106. }
  40107. }
  40108. }
  40109. if (defines._areImageProcessingDirty) {
  40110. if (!this._imageProcessingConfiguration.isReady()) {
  40111. return false;
  40112. }
  40113. }
  40114. if (!engine.getCaps().standardDerivatives) {
  40115. var bufferMesh = null;
  40116. if (mesh.getClassName() === "InstancedMesh") {
  40117. bufferMesh = mesh.sourceMesh;
  40118. }
  40119. else if (mesh.getClassName() === "Mesh") {
  40120. bufferMesh = mesh;
  40121. }
  40122. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40123. bufferMesh.createNormals(true);
  40124. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40125. }
  40126. }
  40127. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40128. if (effect) {
  40129. scene.resetCachedMaterial();
  40130. subMesh.setEffect(effect, defines);
  40131. this.buildUniformLayout();
  40132. }
  40133. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40134. return false;
  40135. }
  40136. defines._renderId = scene.getRenderId();
  40137. this._wasPreviouslyReady = true;
  40138. return true;
  40139. };
  40140. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40141. if (onCompiled === void 0) { onCompiled = null; }
  40142. if (onError === void 0) { onError = null; }
  40143. if (useInstances === void 0) { useInstances = null; }
  40144. if (useClipPlane === void 0) { useClipPlane = null; }
  40145. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40146. if (!defines.isDirty) {
  40147. return null;
  40148. }
  40149. defines.markAsProcessed();
  40150. var scene = this.getScene();
  40151. var engine = scene.getEngine();
  40152. // Fallbacks
  40153. var fallbacks = new BABYLON.EffectFallbacks();
  40154. var fallbackRank = 0;
  40155. if (defines.USESPHERICALINVERTEX) {
  40156. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40157. }
  40158. if (defines.FOG) {
  40159. fallbacks.addFallback(fallbackRank, "FOG");
  40160. }
  40161. if (defines.POINTSIZE) {
  40162. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40163. }
  40164. if (defines.LOGARITHMICDEPTH) {
  40165. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40166. }
  40167. if (defines.PARALLAX) {
  40168. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40169. }
  40170. if (defines.PARALLAXOCCLUSION) {
  40171. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40172. }
  40173. if (defines.ENVIRONMENTBRDF) {
  40174. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40175. }
  40176. if (defines.TANGENT) {
  40177. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40178. }
  40179. if (defines.BUMP) {
  40180. fallbacks.addFallback(fallbackRank++, "BUMP");
  40181. }
  40182. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40183. if (defines.SPECULARTERM) {
  40184. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40185. }
  40186. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40187. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40188. }
  40189. if (defines.LIGHTMAP) {
  40190. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40191. }
  40192. if (defines.NORMAL) {
  40193. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40194. }
  40195. if (defines.AMBIENT) {
  40196. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40197. }
  40198. if (defines.EMISSIVE) {
  40199. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40200. }
  40201. if (defines.VERTEXCOLOR) {
  40202. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40203. }
  40204. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40205. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40206. }
  40207. if (defines.MORPHTARGETS) {
  40208. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40209. }
  40210. //Attributes
  40211. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40212. if (defines.NORMAL) {
  40213. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40214. }
  40215. if (defines.TANGENT) {
  40216. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40217. }
  40218. if (defines.UV1) {
  40219. attribs.push(BABYLON.VertexBuffer.UVKind);
  40220. }
  40221. if (defines.UV2) {
  40222. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40223. }
  40224. if (defines.VERTEXCOLOR) {
  40225. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40226. }
  40227. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40228. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40229. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40230. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40231. "vFogInfos", "vFogColor", "pointSize",
  40232. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40233. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40234. "mBones",
  40235. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40236. "vLightingIntensity",
  40237. "logarithmicDepthConstant",
  40238. "vSphericalX", "vSphericalY", "vSphericalZ",
  40239. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40240. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40241. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40242. "vTangentSpaceParams"
  40243. ];
  40244. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40245. "bumpSampler", "lightmapSampler", "opacitySampler",
  40246. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40247. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40248. "microSurfaceSampler", "environmentBrdfSampler"];
  40249. var uniformBuffers = ["Material", "Scene"];
  40250. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40251. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40252. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40253. uniformsNames: uniforms,
  40254. uniformBuffersNames: uniformBuffers,
  40255. samplers: samplers,
  40256. defines: defines,
  40257. maxSimultaneousLights: this._maxSimultaneousLights
  40258. });
  40259. var join = defines.toString();
  40260. return engine.createEffect("pbr", {
  40261. attributes: attribs,
  40262. uniformsNames: uniforms,
  40263. uniformBuffersNames: uniformBuffers,
  40264. samplers: samplers,
  40265. defines: join,
  40266. fallbacks: fallbacks,
  40267. onCompiled: onCompiled,
  40268. onError: onError,
  40269. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40270. }, engine);
  40271. };
  40272. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40273. if (useInstances === void 0) { useInstances = null; }
  40274. if (useClipPlane === void 0) { useClipPlane = null; }
  40275. var scene = this.getScene();
  40276. var engine = scene.getEngine();
  40277. // Lights
  40278. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40279. defines._needNormals = true;
  40280. // Textures
  40281. if (defines._areTexturesDirty) {
  40282. defines._needUVs = false;
  40283. if (scene.texturesEnabled) {
  40284. if (scene.getEngine().getCaps().textureLOD) {
  40285. defines.LODBASEDMICROSFURACE = true;
  40286. }
  40287. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40288. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40289. }
  40290. else {
  40291. defines.ALBEDO = false;
  40292. }
  40293. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40294. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40295. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40296. }
  40297. else {
  40298. defines.AMBIENT = false;
  40299. }
  40300. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40301. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40302. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40303. }
  40304. else {
  40305. defines.OPACITY = false;
  40306. }
  40307. var reflectionTexture = this._getReflectionTexture();
  40308. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40309. defines.REFLECTION = true;
  40310. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40311. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40312. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40313. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40314. defines.INVERTCUBICMAP = true;
  40315. }
  40316. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40317. switch (reflectionTexture.coordinatesMode) {
  40318. case BABYLON.Texture.CUBIC_MODE:
  40319. case BABYLON.Texture.INVCUBIC_MODE:
  40320. defines.REFLECTIONMAP_CUBIC = true;
  40321. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40322. break;
  40323. case BABYLON.Texture.EXPLICIT_MODE:
  40324. defines.REFLECTIONMAP_EXPLICIT = true;
  40325. break;
  40326. case BABYLON.Texture.PLANAR_MODE:
  40327. defines.REFLECTIONMAP_PLANAR = true;
  40328. break;
  40329. case BABYLON.Texture.PROJECTION_MODE:
  40330. defines.REFLECTIONMAP_PROJECTION = true;
  40331. break;
  40332. case BABYLON.Texture.SKYBOX_MODE:
  40333. defines.REFLECTIONMAP_SKYBOX = true;
  40334. break;
  40335. case BABYLON.Texture.SPHERICAL_MODE:
  40336. defines.REFLECTIONMAP_SPHERICAL = true;
  40337. break;
  40338. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40339. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40340. break;
  40341. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40342. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40343. break;
  40344. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40345. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40346. break;
  40347. }
  40348. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40349. if (reflectionTexture.sphericalPolynomial) {
  40350. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40351. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40352. defines.USESPHERICALINVERTEX = false;
  40353. }
  40354. else {
  40355. defines.USESPHERICALINVERTEX = true;
  40356. }
  40357. }
  40358. }
  40359. }
  40360. else {
  40361. defines.REFLECTION = false;
  40362. defines.REFLECTIONMAP_3D = false;
  40363. defines.REFLECTIONMAP_SPHERICAL = false;
  40364. defines.REFLECTIONMAP_PLANAR = false;
  40365. defines.REFLECTIONMAP_CUBIC = false;
  40366. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40367. defines.REFLECTIONMAP_PROJECTION = false;
  40368. defines.REFLECTIONMAP_SKYBOX = false;
  40369. defines.REFLECTIONMAP_EXPLICIT = false;
  40370. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40371. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40372. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40373. defines.INVERTCUBICMAP = false;
  40374. defines.USESPHERICALFROMREFLECTIONMAP = false;
  40375. defines.USESPHERICALINVERTEX = false;
  40376. defines.REFLECTIONMAP_OPPOSITEZ = false;
  40377. defines.LODINREFLECTIONALPHA = false;
  40378. defines.GAMMAREFLECTION = false;
  40379. }
  40380. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40381. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40382. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40383. }
  40384. else {
  40385. defines.LIGHTMAP = false;
  40386. }
  40387. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40388. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40389. }
  40390. else {
  40391. defines.EMISSIVE = false;
  40392. }
  40393. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40394. if (this._metallicTexture) {
  40395. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  40396. defines.METALLICWORKFLOW = true;
  40397. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  40398. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  40399. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  40400. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  40401. }
  40402. else if (this._reflectivityTexture) {
  40403. defines.METALLICWORKFLOW = false;
  40404. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  40405. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  40406. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  40407. }
  40408. else {
  40409. defines.METALLICWORKFLOW = false;
  40410. defines.REFLECTIVITY = false;
  40411. }
  40412. if (this._microSurfaceTexture) {
  40413. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  40414. }
  40415. else {
  40416. defines.MICROSURFACEMAP = false;
  40417. }
  40418. }
  40419. else {
  40420. defines.REFLECTIVITY = false;
  40421. defines.MICROSURFACEMAP = false;
  40422. }
  40423. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40424. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40425. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40426. defines.PARALLAX = true;
  40427. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40428. }
  40429. else {
  40430. defines.PARALLAX = false;
  40431. }
  40432. }
  40433. else {
  40434. defines.BUMP = false;
  40435. }
  40436. var refractionTexture = this._getRefractionTexture();
  40437. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40438. defines.REFRACTION = true;
  40439. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40440. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40441. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40442. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40443. if (this._linkRefractionWithTransparency) {
  40444. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40445. }
  40446. }
  40447. else {
  40448. defines.REFRACTION = false;
  40449. }
  40450. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40451. defines.ENVIRONMENTBRDF = true;
  40452. }
  40453. else {
  40454. defines.ENVIRONMENTBRDF = false;
  40455. }
  40456. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40457. defines.ALPHAFROMALBEDO = true;
  40458. }
  40459. else {
  40460. defines.ALPHAFROMALBEDO = false;
  40461. }
  40462. }
  40463. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40464. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40465. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40466. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40467. defines.METALLICWORKFLOW = true;
  40468. }
  40469. else {
  40470. defines.METALLICWORKFLOW = false;
  40471. }
  40472. if (!this.backFaceCulling && this._twoSidedLighting) {
  40473. defines.TWOSIDEDLIGHTING = true;
  40474. }
  40475. else {
  40476. defines.TWOSIDEDLIGHTING = false;
  40477. }
  40478. defines.ALPHATESTVALUE = this._alphaCutOff;
  40479. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40480. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40481. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40482. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40483. }
  40484. if (defines._areImageProcessingDirty) {
  40485. this._imageProcessingConfiguration.prepareDefines(defines);
  40486. }
  40487. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40488. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40489. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40490. // Misc.
  40491. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40492. // Values that need to be evaluated on every frame
  40493. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  40494. // Attribs
  40495. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  40496. };
  40497. /**
  40498. * Force shader compilation
  40499. */
  40500. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  40501. var _this = this;
  40502. var localOptions = __assign({ clipPlane: false }, options);
  40503. var defines = new PBRMaterialDefines();
  40504. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  40505. if (effect.isReady()) {
  40506. if (onCompiled) {
  40507. onCompiled(this);
  40508. }
  40509. }
  40510. else {
  40511. effect.onCompileObservable.add(function () {
  40512. if (onCompiled) {
  40513. onCompiled(_this);
  40514. }
  40515. });
  40516. }
  40517. };
  40518. /**
  40519. * Initializes the uniform buffer layout for the shader.
  40520. */
  40521. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40522. // Order is important !
  40523. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40524. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40525. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40526. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40527. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40528. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40529. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40530. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40531. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40532. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40533. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40534. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40535. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40536. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40537. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40538. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40539. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40540. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40541. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40542. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40543. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40544. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40545. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40546. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40547. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40548. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40549. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40550. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40551. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40552. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40553. this._uniformBuffer.addUniform("pointSize", 1);
  40554. this._uniformBuffer.create();
  40555. };
  40556. /**
  40557. * Unbinds the textures.
  40558. */
  40559. PBRBaseMaterial.prototype.unbind = function () {
  40560. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40561. this._uniformBuffer.setTexture("reflectionSampler", null);
  40562. }
  40563. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40564. this._uniformBuffer.setTexture("refractionSampler", null);
  40565. }
  40566. _super.prototype.unbind.call(this);
  40567. };
  40568. /**
  40569. * Binds to the world matrix.
  40570. * @param world - The world matrix.
  40571. */
  40572. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40573. this._activeEffect.setMatrix("world", world);
  40574. };
  40575. /**
  40576. * Binds the submesh data.
  40577. * @param world - The world matrix.
  40578. * @param mesh - The BJS mesh.
  40579. * @param subMesh - A submesh of the BJS mesh.
  40580. */
  40581. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40582. var scene = this.getScene();
  40583. var defines = subMesh._materialDefines;
  40584. if (!defines) {
  40585. return;
  40586. }
  40587. var effect = subMesh.effect;
  40588. if (!effect) {
  40589. return;
  40590. }
  40591. this._activeEffect = effect;
  40592. // Matrices
  40593. this.bindOnlyWorldMatrix(world);
  40594. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40595. // Bones
  40596. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40597. var reflectionTexture = null;
  40598. if (mustRebind) {
  40599. this._uniformBuffer.bindToEffect(effect, "Material");
  40600. this.bindViewProjection(effect);
  40601. reflectionTexture = this._getReflectionTexture();
  40602. var refractionTexture = this._getRefractionTexture();
  40603. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40604. // Texture uniforms
  40605. if (scene.texturesEnabled) {
  40606. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40607. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40608. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40609. }
  40610. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40611. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40612. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40613. }
  40614. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40615. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40616. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40617. }
  40618. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40619. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40620. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40621. if (reflectionTexture.boundingBoxSize) {
  40622. var cubeTexture = reflectionTexture;
  40623. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40624. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40625. }
  40626. var polynomials = reflectionTexture.sphericalPolynomial;
  40627. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  40628. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  40629. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  40630. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  40631. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  40632. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  40633. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  40634. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  40635. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  40636. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  40637. }
  40638. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  40639. }
  40640. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40641. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40642. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40643. }
  40644. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40645. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40646. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40647. }
  40648. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40649. if (this._metallicTexture) {
  40650. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  40651. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  40652. }
  40653. else if (this._reflectivityTexture) {
  40654. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  40655. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  40656. }
  40657. if (this._microSurfaceTexture) {
  40658. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  40659. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  40660. }
  40661. }
  40662. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40663. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  40664. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40665. if (scene._mirroredCameraPosition) {
  40666. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40667. }
  40668. else {
  40669. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40670. }
  40671. }
  40672. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40673. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  40674. var depth = 1.0;
  40675. if (!refractionTexture.isCube) {
  40676. if (refractionTexture.depth) {
  40677. depth = refractionTexture.depth;
  40678. }
  40679. }
  40680. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  40681. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  40682. }
  40683. }
  40684. // Point size
  40685. if (this.pointsCloud) {
  40686. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40687. }
  40688. // Colors
  40689. if (defines.METALLICWORKFLOW) {
  40690. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  40691. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  40692. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  40693. }
  40694. else {
  40695. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  40696. }
  40697. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  40698. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  40699. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  40700. // Misc
  40701. this._lightingInfos.x = this._directIntensity;
  40702. this._lightingInfos.y = this._emissiveIntensity;
  40703. this._lightingInfos.z = this._environmentIntensity;
  40704. this._lightingInfos.w = this._specularIntensity;
  40705. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  40706. }
  40707. // Textures
  40708. if (scene.texturesEnabled) {
  40709. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40710. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  40711. }
  40712. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40713. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  40714. }
  40715. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40716. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  40717. }
  40718. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40719. if (defines.LODBASEDMICROSFURACE) {
  40720. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  40721. }
  40722. else {
  40723. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  40724. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  40725. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  40726. }
  40727. }
  40728. if (defines.ENVIRONMENTBRDF) {
  40729. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  40730. }
  40731. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40732. if (defines.LODBASEDMICROSFURACE) {
  40733. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  40734. }
  40735. else {
  40736. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  40737. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  40738. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  40739. }
  40740. }
  40741. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40742. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  40743. }
  40744. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40745. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  40746. }
  40747. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40748. if (this._metallicTexture) {
  40749. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  40750. }
  40751. else if (this._reflectivityTexture) {
  40752. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  40753. }
  40754. if (this._microSurfaceTexture) {
  40755. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  40756. }
  40757. }
  40758. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40759. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  40760. }
  40761. }
  40762. // Clip plane
  40763. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  40764. // Colors
  40765. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  40766. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40767. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  40768. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  40769. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40770. }
  40771. if (mustRebind || !this.isFrozen) {
  40772. // Lights
  40773. if (scene.lightsEnabled && !this._disableLighting) {
  40774. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  40775. }
  40776. // View
  40777. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  40778. this.bindView(effect);
  40779. }
  40780. // Fog
  40781. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  40782. // Morph targets
  40783. if (defines.NUM_MORPH_INFLUENCERS) {
  40784. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  40785. }
  40786. // image processing
  40787. this._imageProcessingConfiguration.bind(this._activeEffect);
  40788. // Log. depth
  40789. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  40790. }
  40791. this._uniformBuffer.update();
  40792. this._afterBind(mesh);
  40793. };
  40794. /**
  40795. * Returns the animatable textures.
  40796. * @returns - Array of animatable textures.
  40797. */
  40798. PBRBaseMaterial.prototype.getAnimatables = function () {
  40799. var results = [];
  40800. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  40801. results.push(this._albedoTexture);
  40802. }
  40803. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40804. results.push(this._ambientTexture);
  40805. }
  40806. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40807. results.push(this._opacityTexture);
  40808. }
  40809. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40810. results.push(this._reflectionTexture);
  40811. }
  40812. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40813. results.push(this._emissiveTexture);
  40814. }
  40815. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  40816. results.push(this._metallicTexture);
  40817. }
  40818. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  40819. results.push(this._reflectivityTexture);
  40820. }
  40821. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40822. results.push(this._bumpTexture);
  40823. }
  40824. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40825. results.push(this._lightmapTexture);
  40826. }
  40827. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40828. results.push(this._refractionTexture);
  40829. }
  40830. return results;
  40831. };
  40832. /**
  40833. * Returns the texture used for reflections.
  40834. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  40835. */
  40836. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  40837. if (this._reflectionTexture) {
  40838. return this._reflectionTexture;
  40839. }
  40840. return this.getScene().environmentTexture;
  40841. };
  40842. /**
  40843. * Returns the texture used for refraction or null if none is used.
  40844. * @returns - Refection texture if present. If no refraction texture and refraction
  40845. * is linked with transparency, returns environment texture. Otherwise, returns null.
  40846. */
  40847. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  40848. if (this._refractionTexture) {
  40849. return this._refractionTexture;
  40850. }
  40851. if (this._linkRefractionWithTransparency) {
  40852. return this.getScene().environmentTexture;
  40853. }
  40854. return null;
  40855. };
  40856. /**
  40857. * Disposes the resources of the material.
  40858. * @param forceDisposeEffect - Forces the disposal of effects.
  40859. * @param forceDisposeTextures - Forces the disposal of all textures.
  40860. */
  40861. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40862. if (forceDisposeTextures) {
  40863. if (this._albedoTexture) {
  40864. this._albedoTexture.dispose();
  40865. }
  40866. if (this._ambientTexture) {
  40867. this._ambientTexture.dispose();
  40868. }
  40869. if (this._opacityTexture) {
  40870. this._opacityTexture.dispose();
  40871. }
  40872. if (this._reflectionTexture) {
  40873. this._reflectionTexture.dispose();
  40874. }
  40875. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  40876. this._environmentBRDFTexture.dispose();
  40877. }
  40878. if (this._emissiveTexture) {
  40879. this._emissiveTexture.dispose();
  40880. }
  40881. if (this._metallicTexture) {
  40882. this._metallicTexture.dispose();
  40883. }
  40884. if (this._reflectivityTexture) {
  40885. this._reflectivityTexture.dispose();
  40886. }
  40887. if (this._bumpTexture) {
  40888. this._bumpTexture.dispose();
  40889. }
  40890. if (this._lightmapTexture) {
  40891. this._lightmapTexture.dispose();
  40892. }
  40893. if (this._refractionTexture) {
  40894. this._refractionTexture.dispose();
  40895. }
  40896. }
  40897. this._renderTargets.dispose();
  40898. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40899. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40900. }
  40901. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40902. };
  40903. /**
  40904. * Stores the reflectivity values based on metallic roughness workflow.
  40905. */
  40906. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  40907. __decorate([
  40908. BABYLON.serializeAsImageProcessingConfiguration()
  40909. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  40910. __decorate([
  40911. BABYLON.serialize()
  40912. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  40913. __decorate([
  40914. BABYLON.serialize()
  40915. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  40916. return PBRBaseMaterial;
  40917. }(BABYLON.PushMaterial));
  40918. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  40919. })(BABYLON || (BABYLON = {}));
  40920. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  40921. var BABYLON;
  40922. (function (BABYLON) {
  40923. /**
  40924. * The Physically based simple base material of BJS.
  40925. *
  40926. * This enables better naming and convention enforcements on top of the pbrMaterial.
  40927. * It is used as the base class for both the specGloss and metalRough conventions.
  40928. */
  40929. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  40930. __extends(PBRBaseSimpleMaterial, _super);
  40931. /**
  40932. * Instantiates a new PBRMaterial instance.
  40933. *
  40934. * @param name The material name
  40935. * @param scene The scene the material will be use in.
  40936. */
  40937. function PBRBaseSimpleMaterial(name, scene) {
  40938. var _this = _super.call(this, name, scene) || this;
  40939. /**
  40940. * Number of Simultaneous lights allowed on the material.
  40941. */
  40942. _this.maxSimultaneousLights = 4;
  40943. /**
  40944. * If sets to true, disables all the lights affecting the material.
  40945. */
  40946. _this.disableLighting = false;
  40947. /**
  40948. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  40949. */
  40950. _this.invertNormalMapX = false;
  40951. /**
  40952. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  40953. */
  40954. _this.invertNormalMapY = false;
  40955. /**
  40956. * Emissivie color used to self-illuminate the model.
  40957. */
  40958. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  40959. /**
  40960. * Occlusion Channel Strenght.
  40961. */
  40962. _this.occlusionStrength = 1.0;
  40963. _this.useLightmapAsShadowmap = false;
  40964. _this._useAlphaFromAlbedoTexture = true;
  40965. _this._useAmbientInGrayScale = true;
  40966. return _this;
  40967. }
  40968. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  40969. /**
  40970. * Gets the current double sided mode.
  40971. */
  40972. get: function () {
  40973. return this._twoSidedLighting;
  40974. },
  40975. /**
  40976. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40977. */
  40978. set: function (value) {
  40979. if (this._twoSidedLighting === value) {
  40980. return;
  40981. }
  40982. this._twoSidedLighting = value;
  40983. this.backFaceCulling = !value;
  40984. this._markAllSubMeshesAsTexturesDirty();
  40985. },
  40986. enumerable: true,
  40987. configurable: true
  40988. });
  40989. /**
  40990. * Return the active textures of the material.
  40991. */
  40992. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  40993. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40994. if (this.environmentTexture) {
  40995. activeTextures.push(this.environmentTexture);
  40996. }
  40997. if (this.normalTexture) {
  40998. activeTextures.push(this.normalTexture);
  40999. }
  41000. if (this.emissiveTexture) {
  41001. activeTextures.push(this.emissiveTexture);
  41002. }
  41003. if (this.occlusionTexture) {
  41004. activeTextures.push(this.occlusionTexture);
  41005. }
  41006. if (this.lightmapTexture) {
  41007. activeTextures.push(this.lightmapTexture);
  41008. }
  41009. return activeTextures;
  41010. };
  41011. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41012. if (_super.prototype.hasTexture.call(this, texture)) {
  41013. return true;
  41014. }
  41015. if (this.lightmapTexture === texture) {
  41016. return true;
  41017. }
  41018. return false;
  41019. };
  41020. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41021. return "PBRBaseSimpleMaterial";
  41022. };
  41023. __decorate([
  41024. BABYLON.serialize(),
  41025. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41026. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41027. __decorate([
  41028. BABYLON.serialize(),
  41029. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41030. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41031. __decorate([
  41032. BABYLON.serializeAsTexture(),
  41033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41034. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41035. __decorate([
  41036. BABYLON.serialize(),
  41037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41038. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41039. __decorate([
  41040. BABYLON.serialize(),
  41041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41042. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41043. __decorate([
  41044. BABYLON.serializeAsTexture(),
  41045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41046. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41047. __decorate([
  41048. BABYLON.serializeAsColor3("emissive"),
  41049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41050. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41051. __decorate([
  41052. BABYLON.serializeAsTexture(),
  41053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41054. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41055. __decorate([
  41056. BABYLON.serialize(),
  41057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41058. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41059. __decorate([
  41060. BABYLON.serializeAsTexture(),
  41061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41062. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41063. __decorate([
  41064. BABYLON.serialize(),
  41065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41066. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41067. __decorate([
  41068. BABYLON.serialize()
  41069. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41070. __decorate([
  41071. BABYLON.serializeAsTexture(),
  41072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41073. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41074. __decorate([
  41075. BABYLON.serialize(),
  41076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41077. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41078. return PBRBaseSimpleMaterial;
  41079. }(BABYLON.PBRBaseMaterial));
  41080. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41081. })(BABYLON || (BABYLON = {}));
  41082. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41083. var BABYLON;
  41084. (function (BABYLON) {
  41085. /**
  41086. * The Physically based material of BJS.
  41087. *
  41088. * This offers the main features of a standard PBR material.
  41089. * For more information, please refer to the documentation :
  41090. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41091. */
  41092. var PBRMaterial = /** @class */ (function (_super) {
  41093. __extends(PBRMaterial, _super);
  41094. /**
  41095. * Instantiates a new PBRMaterial instance.
  41096. *
  41097. * @param name The material name
  41098. * @param scene The scene the material will be use in.
  41099. */
  41100. function PBRMaterial(name, scene) {
  41101. var _this = _super.call(this, name, scene) || this;
  41102. /**
  41103. * Intensity of the direct lights e.g. the four lights available in your scene.
  41104. * This impacts both the direct diffuse and specular highlights.
  41105. */
  41106. _this.directIntensity = 1.0;
  41107. /**
  41108. * Intensity of the emissive part of the material.
  41109. * This helps controlling the emissive effect without modifying the emissive color.
  41110. */
  41111. _this.emissiveIntensity = 1.0;
  41112. /**
  41113. * Intensity of the environment e.g. how much the environment will light the object
  41114. * either through harmonics for rough material or through the refelction for shiny ones.
  41115. */
  41116. _this.environmentIntensity = 1.0;
  41117. /**
  41118. * This is a special control allowing the reduction of the specular highlights coming from the
  41119. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41120. */
  41121. _this.specularIntensity = 1.0;
  41122. /**
  41123. * Debug Control allowing disabling the bump map on this material.
  41124. */
  41125. _this.disableBumpMap = false;
  41126. /**
  41127. * AKA Occlusion Texture Intensity in other nomenclature.
  41128. */
  41129. _this.ambientTextureStrength = 1.0;
  41130. /**
  41131. * The color of a material in ambient lighting.
  41132. */
  41133. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41134. /**
  41135. * AKA Diffuse Color in other nomenclature.
  41136. */
  41137. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41138. /**
  41139. * AKA Specular Color in other nomenclature.
  41140. */
  41141. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41142. /**
  41143. * The color reflected from the material.
  41144. */
  41145. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41146. /**
  41147. * The color emitted from the material.
  41148. */
  41149. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41150. /**
  41151. * AKA Glossiness in other nomenclature.
  41152. */
  41153. _this.microSurface = 1.0;
  41154. /**
  41155. * source material index of refraction (IOR)' / 'destination material IOR.
  41156. */
  41157. _this.indexOfRefraction = 0.66;
  41158. /**
  41159. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41160. */
  41161. _this.invertRefractionY = false;
  41162. /**
  41163. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41164. * Materials half opaque for instance using refraction could benefit from this control.
  41165. */
  41166. _this.linkRefractionWithTransparency = false;
  41167. _this.useLightmapAsShadowmap = false;
  41168. /**
  41169. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41170. */
  41171. _this.useAlphaFromAlbedoTexture = false;
  41172. /**
  41173. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41174. */
  41175. _this.forceAlphaTest = false;
  41176. /**
  41177. * Defines the alpha limits in alpha test mode.
  41178. */
  41179. _this.alphaCutOff = 0.4;
  41180. /**
  41181. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41182. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41183. */
  41184. _this.useSpecularOverAlpha = true;
  41185. /**
  41186. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41187. */
  41188. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41189. /**
  41190. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41191. */
  41192. _this.useRoughnessFromMetallicTextureAlpha = true;
  41193. /**
  41194. * Specifies if the metallic texture contains the roughness information in its green channel.
  41195. */
  41196. _this.useRoughnessFromMetallicTextureGreen = false;
  41197. /**
  41198. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41199. */
  41200. _this.useMetallnessFromMetallicTextureBlue = false;
  41201. /**
  41202. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41203. */
  41204. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41205. /**
  41206. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41207. */
  41208. _this.useAmbientInGrayScale = false;
  41209. /**
  41210. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41211. * The material will try to infer what glossiness each pixel should be.
  41212. */
  41213. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41214. /**
  41215. * BJS is using an harcoded light falloff based on a manually sets up range.
  41216. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41217. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41218. */
  41219. _this.usePhysicalLightFalloff = true;
  41220. /**
  41221. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41222. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41223. */
  41224. _this.useRadianceOverAlpha = true;
  41225. /**
  41226. * Allows using the bump map in parallax mode.
  41227. */
  41228. _this.useParallax = false;
  41229. /**
  41230. * Allows using the bump map in parallax occlusion mode.
  41231. */
  41232. _this.useParallaxOcclusion = false;
  41233. /**
  41234. * Controls the scale bias of the parallax mode.
  41235. */
  41236. _this.parallaxScaleBias = 0.05;
  41237. /**
  41238. * If sets to true, disables all the lights affecting the material.
  41239. */
  41240. _this.disableLighting = false;
  41241. /**
  41242. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41243. */
  41244. _this.forceIrradianceInFragment = false;
  41245. /**
  41246. * Number of Simultaneous lights allowed on the material.
  41247. */
  41248. _this.maxSimultaneousLights = 4;
  41249. /**
  41250. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41251. */
  41252. _this.invertNormalMapX = false;
  41253. /**
  41254. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41255. */
  41256. _this.invertNormalMapY = false;
  41257. /**
  41258. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41259. */
  41260. _this.twoSidedLighting = false;
  41261. /**
  41262. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41263. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41264. */
  41265. _this.useAlphaFresnel = false;
  41266. /**
  41267. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41268. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41269. */
  41270. _this.useLinearAlphaFresnel = false;
  41271. /**
  41272. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41273. * And/Or occlude the blended part.
  41274. */
  41275. _this.environmentBRDFTexture = null;
  41276. /**
  41277. * Force normal to face away from face.
  41278. */
  41279. _this.forceNormalForward = false;
  41280. /**
  41281. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41282. * makes the reflect vector face the model (under horizon).
  41283. */
  41284. _this.useHorizonOcclusion = true;
  41285. /**
  41286. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41287. * too much the area relying on ambient texture to define their ambient occlusion.
  41288. */
  41289. _this.useRadianceOcclusion = true;
  41290. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41291. return _this;
  41292. }
  41293. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41294. /**
  41295. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41296. */
  41297. get: function () {
  41298. return this._PBRMATERIAL_OPAQUE;
  41299. },
  41300. enumerable: true,
  41301. configurable: true
  41302. });
  41303. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41304. /**
  41305. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41306. */
  41307. get: function () {
  41308. return this._PBRMATERIAL_ALPHATEST;
  41309. },
  41310. enumerable: true,
  41311. configurable: true
  41312. });
  41313. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41314. /**
  41315. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41316. */
  41317. get: function () {
  41318. return this._PBRMATERIAL_ALPHABLEND;
  41319. },
  41320. enumerable: true,
  41321. configurable: true
  41322. });
  41323. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41324. /**
  41325. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41326. * They are also discarded below the alpha cutoff threshold to improve performances.
  41327. */
  41328. get: function () {
  41329. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41330. },
  41331. enumerable: true,
  41332. configurable: true
  41333. });
  41334. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41335. /**
  41336. * Gets the image processing configuration used either in this material.
  41337. */
  41338. get: function () {
  41339. return this._imageProcessingConfiguration;
  41340. },
  41341. /**
  41342. * Sets the Default image processing configuration used either in the this material.
  41343. *
  41344. * If sets to null, the scene one is in use.
  41345. */
  41346. set: function (value) {
  41347. this._attachImageProcessingConfiguration(value);
  41348. // Ensure the effect will be rebuilt.
  41349. this._markAllSubMeshesAsTexturesDirty();
  41350. },
  41351. enumerable: true,
  41352. configurable: true
  41353. });
  41354. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41355. /**
  41356. * Gets wether the color curves effect is enabled.
  41357. */
  41358. get: function () {
  41359. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41360. },
  41361. /**
  41362. * Sets wether the color curves effect is enabled.
  41363. */
  41364. set: function (value) {
  41365. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41366. },
  41367. enumerable: true,
  41368. configurable: true
  41369. });
  41370. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41371. /**
  41372. * Gets wether the color grading effect is enabled.
  41373. */
  41374. get: function () {
  41375. return this.imageProcessingConfiguration.colorGradingEnabled;
  41376. },
  41377. /**
  41378. * Gets wether the color grading effect is enabled.
  41379. */
  41380. set: function (value) {
  41381. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41382. },
  41383. enumerable: true,
  41384. configurable: true
  41385. });
  41386. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41387. /**
  41388. * Gets wether tonemapping is enabled or not.
  41389. */
  41390. get: function () {
  41391. return this._imageProcessingConfiguration.toneMappingEnabled;
  41392. },
  41393. /**
  41394. * Sets wether tonemapping is enabled or not
  41395. */
  41396. set: function (value) {
  41397. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41398. },
  41399. enumerable: true,
  41400. configurable: true
  41401. });
  41402. ;
  41403. ;
  41404. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41405. /**
  41406. * The camera exposure used on this material.
  41407. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41408. * This corresponds to a photographic exposure.
  41409. */
  41410. get: function () {
  41411. return this._imageProcessingConfiguration.exposure;
  41412. },
  41413. /**
  41414. * The camera exposure used on this material.
  41415. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41416. * This corresponds to a photographic exposure.
  41417. */
  41418. set: function (value) {
  41419. this._imageProcessingConfiguration.exposure = value;
  41420. },
  41421. enumerable: true,
  41422. configurable: true
  41423. });
  41424. ;
  41425. ;
  41426. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41427. /**
  41428. * Gets The camera contrast used on this material.
  41429. */
  41430. get: function () {
  41431. return this._imageProcessingConfiguration.contrast;
  41432. },
  41433. /**
  41434. * Sets The camera contrast used on this material.
  41435. */
  41436. set: function (value) {
  41437. this._imageProcessingConfiguration.contrast = value;
  41438. },
  41439. enumerable: true,
  41440. configurable: true
  41441. });
  41442. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41443. /**
  41444. * Gets the Color Grading 2D Lookup Texture.
  41445. */
  41446. get: function () {
  41447. return this._imageProcessingConfiguration.colorGradingTexture;
  41448. },
  41449. /**
  41450. * Sets the Color Grading 2D Lookup Texture.
  41451. */
  41452. set: function (value) {
  41453. this._imageProcessingConfiguration.colorGradingTexture = value;
  41454. },
  41455. enumerable: true,
  41456. configurable: true
  41457. });
  41458. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41459. /**
  41460. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41461. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41462. * 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;
  41463. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41464. */
  41465. get: function () {
  41466. return this._imageProcessingConfiguration.colorCurves;
  41467. },
  41468. /**
  41469. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41470. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41471. * 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;
  41472. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41473. */
  41474. set: function (value) {
  41475. this._imageProcessingConfiguration.colorCurves = value;
  41476. },
  41477. enumerable: true,
  41478. configurable: true
  41479. });
  41480. /**
  41481. * Returns the name of this material class.
  41482. */
  41483. PBRMaterial.prototype.getClassName = function () {
  41484. return "PBRMaterial";
  41485. };
  41486. /**
  41487. * Returns an array of the actively used textures.
  41488. * @returns - Array of BaseTextures
  41489. */
  41490. PBRMaterial.prototype.getActiveTextures = function () {
  41491. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41492. if (this._albedoTexture) {
  41493. activeTextures.push(this._albedoTexture);
  41494. }
  41495. if (this._ambientTexture) {
  41496. activeTextures.push(this._ambientTexture);
  41497. }
  41498. if (this._opacityTexture) {
  41499. activeTextures.push(this._opacityTexture);
  41500. }
  41501. if (this._reflectionTexture) {
  41502. activeTextures.push(this._reflectionTexture);
  41503. }
  41504. if (this._emissiveTexture) {
  41505. activeTextures.push(this._emissiveTexture);
  41506. }
  41507. if (this._reflectivityTexture) {
  41508. activeTextures.push(this._reflectivityTexture);
  41509. }
  41510. if (this._metallicTexture) {
  41511. activeTextures.push(this._metallicTexture);
  41512. }
  41513. if (this._microSurfaceTexture) {
  41514. activeTextures.push(this._microSurfaceTexture);
  41515. }
  41516. if (this._bumpTexture) {
  41517. activeTextures.push(this._bumpTexture);
  41518. }
  41519. if (this._lightmapTexture) {
  41520. activeTextures.push(this._lightmapTexture);
  41521. }
  41522. if (this._refractionTexture) {
  41523. activeTextures.push(this._refractionTexture);
  41524. }
  41525. return activeTextures;
  41526. };
  41527. /**
  41528. * Checks to see if a texture is used in the material.
  41529. * @param texture - Base texture to use.
  41530. * @returns - Boolean specifying if a texture is used in the material.
  41531. */
  41532. PBRMaterial.prototype.hasTexture = function (texture) {
  41533. if (_super.prototype.hasTexture.call(this, texture)) {
  41534. return true;
  41535. }
  41536. if (this._albedoTexture === texture) {
  41537. return true;
  41538. }
  41539. if (this._ambientTexture === texture) {
  41540. return true;
  41541. }
  41542. if (this._opacityTexture === texture) {
  41543. return true;
  41544. }
  41545. if (this._reflectionTexture === texture) {
  41546. return true;
  41547. }
  41548. if (this._reflectivityTexture === texture) {
  41549. return true;
  41550. }
  41551. if (this._metallicTexture === texture) {
  41552. return true;
  41553. }
  41554. if (this._microSurfaceTexture === texture) {
  41555. return true;
  41556. }
  41557. if (this._bumpTexture === texture) {
  41558. return true;
  41559. }
  41560. if (this._lightmapTexture === texture) {
  41561. return true;
  41562. }
  41563. if (this._refractionTexture === texture) {
  41564. return true;
  41565. }
  41566. return false;
  41567. };
  41568. /**
  41569. * Makes a duplicate of the current material.
  41570. * @param name - name to use for the new material.
  41571. */
  41572. PBRMaterial.prototype.clone = function (name) {
  41573. var _this = this;
  41574. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41575. clone.id = name;
  41576. clone.name = name;
  41577. return clone;
  41578. };
  41579. /**
  41580. * Serializes this PBR Material.
  41581. * @returns - An object with the serialized material.
  41582. */
  41583. PBRMaterial.prototype.serialize = function () {
  41584. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41585. serializationObject.customType = "BABYLON.PBRMaterial";
  41586. return serializationObject;
  41587. };
  41588. // Statics
  41589. /**
  41590. * Parses a PBR Material from a serialized object.
  41591. * @param source - Serialized object.
  41592. * @param scene - BJS scene instance.
  41593. * @param rootUrl - url for the scene object
  41594. * @returns - PBRMaterial
  41595. */
  41596. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41597. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41598. };
  41599. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41600. /**
  41601. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41602. */
  41603. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41604. /**
  41605. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41606. */
  41607. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41608. /**
  41609. * 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.
  41610. * They are also discarded below the alpha cutoff threshold to improve performances.
  41611. */
  41612. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41613. __decorate([
  41614. BABYLON.serialize(),
  41615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41616. ], PBRMaterial.prototype, "directIntensity", void 0);
  41617. __decorate([
  41618. BABYLON.serialize(),
  41619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41620. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  41621. __decorate([
  41622. BABYLON.serialize(),
  41623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41624. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  41625. __decorate([
  41626. BABYLON.serialize(),
  41627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41628. ], PBRMaterial.prototype, "specularIntensity", void 0);
  41629. __decorate([
  41630. BABYLON.serialize(),
  41631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41632. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  41633. __decorate([
  41634. BABYLON.serializeAsTexture(),
  41635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41636. ], PBRMaterial.prototype, "albedoTexture", void 0);
  41637. __decorate([
  41638. BABYLON.serializeAsTexture(),
  41639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41640. ], PBRMaterial.prototype, "ambientTexture", void 0);
  41641. __decorate([
  41642. BABYLON.serialize(),
  41643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41644. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  41645. __decorate([
  41646. BABYLON.serializeAsTexture(),
  41647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41648. ], PBRMaterial.prototype, "opacityTexture", void 0);
  41649. __decorate([
  41650. BABYLON.serializeAsTexture(),
  41651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41652. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  41653. __decorate([
  41654. BABYLON.serializeAsTexture(),
  41655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41656. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  41657. __decorate([
  41658. BABYLON.serializeAsTexture(),
  41659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41660. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  41661. __decorate([
  41662. BABYLON.serializeAsTexture(),
  41663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41664. ], PBRMaterial.prototype, "metallicTexture", void 0);
  41665. __decorate([
  41666. BABYLON.serialize(),
  41667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41668. ], PBRMaterial.prototype, "metallic", void 0);
  41669. __decorate([
  41670. BABYLON.serialize(),
  41671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41672. ], PBRMaterial.prototype, "roughness", void 0);
  41673. __decorate([
  41674. BABYLON.serializeAsTexture(),
  41675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41676. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  41677. __decorate([
  41678. BABYLON.serializeAsTexture(),
  41679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41680. ], PBRMaterial.prototype, "bumpTexture", void 0);
  41681. __decorate([
  41682. BABYLON.serializeAsTexture(),
  41683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41684. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  41685. __decorate([
  41686. BABYLON.serializeAsTexture(),
  41687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41688. ], PBRMaterial.prototype, "refractionTexture", void 0);
  41689. __decorate([
  41690. BABYLON.serializeAsColor3("ambient"),
  41691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41692. ], PBRMaterial.prototype, "ambientColor", void 0);
  41693. __decorate([
  41694. BABYLON.serializeAsColor3("albedo"),
  41695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41696. ], PBRMaterial.prototype, "albedoColor", void 0);
  41697. __decorate([
  41698. BABYLON.serializeAsColor3("reflectivity"),
  41699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41700. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  41701. __decorate([
  41702. BABYLON.serializeAsColor3("reflection"),
  41703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41704. ], PBRMaterial.prototype, "reflectionColor", void 0);
  41705. __decorate([
  41706. BABYLON.serializeAsColor3("emissive"),
  41707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41708. ], PBRMaterial.prototype, "emissiveColor", void 0);
  41709. __decorate([
  41710. BABYLON.serialize(),
  41711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41712. ], PBRMaterial.prototype, "microSurface", void 0);
  41713. __decorate([
  41714. BABYLON.serialize(),
  41715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41716. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  41717. __decorate([
  41718. BABYLON.serialize(),
  41719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41720. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  41721. __decorate([
  41722. BABYLON.serialize(),
  41723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41724. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  41725. __decorate([
  41726. BABYLON.serialize(),
  41727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41728. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41729. __decorate([
  41730. BABYLON.serialize(),
  41731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41732. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  41733. __decorate([
  41734. BABYLON.serialize(),
  41735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41736. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  41737. __decorate([
  41738. BABYLON.serialize(),
  41739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41740. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  41741. __decorate([
  41742. BABYLON.serialize(),
  41743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41744. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  41745. __decorate([
  41746. BABYLON.serialize(),
  41747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41748. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  41749. __decorate([
  41750. BABYLON.serialize(),
  41751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41752. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  41753. __decorate([
  41754. BABYLON.serialize(),
  41755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41756. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  41757. __decorate([
  41758. BABYLON.serialize(),
  41759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41760. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  41761. __decorate([
  41762. BABYLON.serialize(),
  41763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41764. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  41765. __decorate([
  41766. BABYLON.serialize(),
  41767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41768. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  41769. __decorate([
  41770. BABYLON.serialize(),
  41771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41772. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  41773. __decorate([
  41774. BABYLON.serialize(),
  41775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41776. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  41777. __decorate([
  41778. BABYLON.serialize(),
  41779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41780. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  41781. __decorate([
  41782. BABYLON.serialize(),
  41783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41784. ], PBRMaterial.prototype, "useParallax", void 0);
  41785. __decorate([
  41786. BABYLON.serialize(),
  41787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41788. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  41789. __decorate([
  41790. BABYLON.serialize(),
  41791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41792. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  41793. __decorate([
  41794. BABYLON.serialize(),
  41795. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41796. ], PBRMaterial.prototype, "disableLighting", void 0);
  41797. __decorate([
  41798. BABYLON.serialize(),
  41799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41800. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  41801. __decorate([
  41802. BABYLON.serialize(),
  41803. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41804. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  41805. __decorate([
  41806. BABYLON.serialize(),
  41807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41808. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  41809. __decorate([
  41810. BABYLON.serialize(),
  41811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41812. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  41813. __decorate([
  41814. BABYLON.serialize(),
  41815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41816. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  41817. __decorate([
  41818. BABYLON.serialize(),
  41819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41820. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  41821. __decorate([
  41822. BABYLON.serialize(),
  41823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41824. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  41825. __decorate([
  41826. BABYLON.serializeAsTexture(),
  41827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41828. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  41829. __decorate([
  41830. BABYLON.serialize(),
  41831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41832. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  41833. __decorate([
  41834. BABYLON.serialize(),
  41835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41836. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  41837. __decorate([
  41838. BABYLON.serialize(),
  41839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41840. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  41841. return PBRMaterial;
  41842. }(BABYLON.PBRBaseMaterial));
  41843. BABYLON.PBRMaterial = PBRMaterial;
  41844. })(BABYLON || (BABYLON = {}));
  41845. //# sourceMappingURL=babylon.pbrMaterial.js.map
  41846. var BABYLON;
  41847. (function (BABYLON) {
  41848. /**
  41849. * The PBR material of BJS following the metal roughness convention.
  41850. *
  41851. * This fits to the PBR convention in the GLTF definition:
  41852. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  41853. */
  41854. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  41855. __extends(PBRMetallicRoughnessMaterial, _super);
  41856. /**
  41857. * Instantiates a new PBRMetalRoughnessMaterial instance.
  41858. *
  41859. * @param name The material name
  41860. * @param scene The scene the material will be use in.
  41861. */
  41862. function PBRMetallicRoughnessMaterial(name, scene) {
  41863. var _this = _super.call(this, name, scene) || this;
  41864. _this._useRoughnessFromMetallicTextureAlpha = false;
  41865. _this._useRoughnessFromMetallicTextureGreen = true;
  41866. _this._useMetallnessFromMetallicTextureBlue = true;
  41867. _this._forceMetallicWorkflow = true;
  41868. return _this;
  41869. }
  41870. /**
  41871. * Return the currrent class name of the material.
  41872. */
  41873. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  41874. return "PBRMetallicRoughnessMaterial";
  41875. };
  41876. /**
  41877. * Return the active textures of the material.
  41878. */
  41879. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  41880. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41881. if (this.baseTexture) {
  41882. activeTextures.push(this.baseTexture);
  41883. }
  41884. if (this.metallicRoughnessTexture) {
  41885. activeTextures.push(this.metallicRoughnessTexture);
  41886. }
  41887. return activeTextures;
  41888. };
  41889. /**
  41890. * Checks to see if a texture is used in the material.
  41891. * @param texture - Base texture to use.
  41892. * @returns - Boolean specifying if a texture is used in the material.
  41893. */
  41894. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  41895. if (_super.prototype.hasTexture.call(this, texture)) {
  41896. return true;
  41897. }
  41898. if (this.baseTexture === texture) {
  41899. return true;
  41900. }
  41901. if (this.metallicRoughnessTexture === texture) {
  41902. return true;
  41903. }
  41904. return false;
  41905. };
  41906. /**
  41907. * Makes a duplicate of the current material.
  41908. * @param name - name to use for the new material.
  41909. */
  41910. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  41911. var _this = this;
  41912. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  41913. clone.id = name;
  41914. clone.name = name;
  41915. return clone;
  41916. };
  41917. /**
  41918. * Serialize the material to a parsable JSON object.
  41919. */
  41920. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  41921. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41922. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  41923. return serializationObject;
  41924. };
  41925. /**
  41926. * Parses a JSON object correponding to the serialize function.
  41927. */
  41928. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  41929. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  41930. };
  41931. __decorate([
  41932. BABYLON.serializeAsColor3(),
  41933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  41934. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  41935. __decorate([
  41936. BABYLON.serializeAsTexture(),
  41937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  41938. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  41939. __decorate([
  41940. BABYLON.serialize(),
  41941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41942. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  41943. __decorate([
  41944. BABYLON.serialize(),
  41945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41946. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  41947. __decorate([
  41948. BABYLON.serializeAsTexture(),
  41949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  41950. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  41951. return PBRMetallicRoughnessMaterial;
  41952. }(BABYLON.PBRBaseSimpleMaterial));
  41953. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  41954. })(BABYLON || (BABYLON = {}));
  41955. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  41956. var BABYLON;
  41957. (function (BABYLON) {
  41958. /**
  41959. * The PBR material of BJS following the specular glossiness convention.
  41960. *
  41961. * This fits to the PBR convention in the GLTF definition:
  41962. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  41963. */
  41964. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  41965. __extends(PBRSpecularGlossinessMaterial, _super);
  41966. /**
  41967. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  41968. *
  41969. * @param name The material name
  41970. * @param scene The scene the material will be use in.
  41971. */
  41972. function PBRSpecularGlossinessMaterial(name, scene) {
  41973. var _this = _super.call(this, name, scene) || this;
  41974. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  41975. return _this;
  41976. }
  41977. /**
  41978. * Return the currrent class name of the material.
  41979. */
  41980. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  41981. return "PBRSpecularGlossinessMaterial";
  41982. };
  41983. /**
  41984. * Return the active textures of the material.
  41985. */
  41986. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  41987. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41988. if (this.diffuseTexture) {
  41989. activeTextures.push(this.diffuseTexture);
  41990. }
  41991. if (this.specularGlossinessTexture) {
  41992. activeTextures.push(this.specularGlossinessTexture);
  41993. }
  41994. return activeTextures;
  41995. };
  41996. /**
  41997. * Checks to see if a texture is used in the material.
  41998. * @param texture - Base texture to use.
  41999. * @returns - Boolean specifying if a texture is used in the material.
  42000. */
  42001. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42002. if (_super.prototype.hasTexture.call(this, texture)) {
  42003. return true;
  42004. }
  42005. if (this.diffuseTexture === texture) {
  42006. return true;
  42007. }
  42008. if (this.specularGlossinessTexture === texture) {
  42009. return true;
  42010. }
  42011. return false;
  42012. };
  42013. /**
  42014. * Makes a duplicate of the current material.
  42015. * @param name - name to use for the new material.
  42016. */
  42017. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42018. var _this = this;
  42019. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42020. clone.id = name;
  42021. clone.name = name;
  42022. return clone;
  42023. };
  42024. /**
  42025. * Serialize the material to a parsable JSON object.
  42026. */
  42027. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42028. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42029. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42030. return serializationObject;
  42031. };
  42032. /**
  42033. * Parses a JSON object correponding to the serialize function.
  42034. */
  42035. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42036. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42037. };
  42038. __decorate([
  42039. BABYLON.serializeAsColor3("diffuse"),
  42040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42041. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42042. __decorate([
  42043. BABYLON.serializeAsTexture(),
  42044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42045. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42046. __decorate([
  42047. BABYLON.serializeAsColor3("specular"),
  42048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42049. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42050. __decorate([
  42051. BABYLON.serialize(),
  42052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42053. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42054. __decorate([
  42055. BABYLON.serializeAsTexture(),
  42056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42057. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42058. return PBRSpecularGlossinessMaterial;
  42059. }(BABYLON.PBRBaseSimpleMaterial));
  42060. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42061. })(BABYLON || (BABYLON = {}));
  42062. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42063. var BABYLON;
  42064. (function (BABYLON) {
  42065. BABYLON.CameraInputTypes = {};
  42066. var CameraInputsManager = /** @class */ (function () {
  42067. function CameraInputsManager(camera) {
  42068. this.attached = {};
  42069. this.camera = camera;
  42070. this.checkInputs = function () { };
  42071. }
  42072. /**
  42073. * Add an input method to a camera.
  42074. * builtin inputs example: camera.inputs.addGamepad();
  42075. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42076. * @param input camera input method
  42077. */
  42078. CameraInputsManager.prototype.add = function (input) {
  42079. var type = input.getSimpleName();
  42080. if (this.attached[type]) {
  42081. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42082. return;
  42083. }
  42084. this.attached[type] = input;
  42085. input.camera = this.camera;
  42086. //for checkInputs, we are dynamically creating a function
  42087. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42088. if (input.checkInputs) {
  42089. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42090. }
  42091. if (this.attachedElement) {
  42092. input.attachControl(this.attachedElement);
  42093. }
  42094. };
  42095. /**
  42096. * Remove a specific input method from a camera
  42097. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42098. * @param inputToRemove camera input method
  42099. */
  42100. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42101. for (var cam in this.attached) {
  42102. var input = this.attached[cam];
  42103. if (input === inputToRemove) {
  42104. input.detachControl(this.attachedElement);
  42105. input.camera = null;
  42106. delete this.attached[cam];
  42107. this.rebuildInputCheck();
  42108. }
  42109. }
  42110. };
  42111. CameraInputsManager.prototype.removeByType = function (inputType) {
  42112. for (var cam in this.attached) {
  42113. var input = this.attached[cam];
  42114. if (input.getClassName() === inputType) {
  42115. input.detachControl(this.attachedElement);
  42116. input.camera = null;
  42117. delete this.attached[cam];
  42118. this.rebuildInputCheck();
  42119. }
  42120. }
  42121. };
  42122. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42123. var current = this.checkInputs;
  42124. return function () {
  42125. current();
  42126. fn();
  42127. };
  42128. };
  42129. CameraInputsManager.prototype.attachInput = function (input) {
  42130. if (this.attachedElement) {
  42131. input.attachControl(this.attachedElement, this.noPreventDefault);
  42132. }
  42133. };
  42134. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42135. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42136. if (this.attachedElement) {
  42137. return;
  42138. }
  42139. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42140. this.attachedElement = element;
  42141. this.noPreventDefault = noPreventDefault;
  42142. for (var cam in this.attached) {
  42143. this.attached[cam].attachControl(element, noPreventDefault);
  42144. }
  42145. };
  42146. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42147. if (disconnect === void 0) { disconnect = false; }
  42148. if (this.attachedElement !== element) {
  42149. return;
  42150. }
  42151. for (var cam in this.attached) {
  42152. this.attached[cam].detachControl(element);
  42153. if (disconnect) {
  42154. this.attached[cam].camera = null;
  42155. }
  42156. }
  42157. this.attachedElement = null;
  42158. };
  42159. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42160. this.checkInputs = function () { };
  42161. for (var cam in this.attached) {
  42162. var input = this.attached[cam];
  42163. if (input.checkInputs) {
  42164. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42165. }
  42166. }
  42167. };
  42168. /**
  42169. * Remove all attached input methods from a camera
  42170. */
  42171. CameraInputsManager.prototype.clear = function () {
  42172. if (this.attachedElement) {
  42173. this.detachElement(this.attachedElement, true);
  42174. }
  42175. this.attached = {};
  42176. this.attachedElement = null;
  42177. this.checkInputs = function () { };
  42178. };
  42179. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42180. var inputs = {};
  42181. for (var cam in this.attached) {
  42182. var input = this.attached[cam];
  42183. var res = BABYLON.SerializationHelper.Serialize(input);
  42184. inputs[input.getClassName()] = res;
  42185. }
  42186. serializedCamera.inputsmgr = inputs;
  42187. };
  42188. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42189. var parsedInputs = parsedCamera.inputsmgr;
  42190. if (parsedInputs) {
  42191. this.clear();
  42192. for (var n in parsedInputs) {
  42193. var construct = BABYLON.CameraInputTypes[n];
  42194. if (construct) {
  42195. var parsedinput = parsedInputs[n];
  42196. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42197. this.add(input);
  42198. }
  42199. }
  42200. }
  42201. else {
  42202. //2016-03-08 this part is for managing backward compatibility
  42203. for (var n in this.attached) {
  42204. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42205. if (construct) {
  42206. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42207. this.remove(this.attached[n]);
  42208. this.add(input);
  42209. }
  42210. }
  42211. }
  42212. };
  42213. return CameraInputsManager;
  42214. }());
  42215. BABYLON.CameraInputsManager = CameraInputsManager;
  42216. })(BABYLON || (BABYLON = {}));
  42217. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42218. var BABYLON;
  42219. (function (BABYLON) {
  42220. var TargetCamera = /** @class */ (function (_super) {
  42221. __extends(TargetCamera, _super);
  42222. function TargetCamera(name, position, scene) {
  42223. var _this = _super.call(this, name, position, scene) || this;
  42224. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42225. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42226. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42227. _this.speed = 2.0;
  42228. _this.noRotationConstraint = false;
  42229. _this.lockedTarget = null;
  42230. _this._currentTarget = BABYLON.Vector3.Zero();
  42231. _this._viewMatrix = BABYLON.Matrix.Zero();
  42232. _this._camMatrix = BABYLON.Matrix.Zero();
  42233. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42234. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42235. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42236. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42237. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42238. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42239. _this._tempMatrix = BABYLON.Matrix.Zero();
  42240. return _this;
  42241. }
  42242. TargetCamera.prototype.getFrontPosition = function (distance) {
  42243. this.getWorldMatrix();
  42244. var direction = this.getTarget().subtract(this.position);
  42245. direction.normalize();
  42246. direction.scaleInPlace(distance);
  42247. return this.globalPosition.add(direction);
  42248. };
  42249. TargetCamera.prototype._getLockedTargetPosition = function () {
  42250. if (!this.lockedTarget) {
  42251. return null;
  42252. }
  42253. if (this.lockedTarget.absolutePosition) {
  42254. this.lockedTarget.computeWorldMatrix();
  42255. }
  42256. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42257. };
  42258. TargetCamera.prototype.storeState = function () {
  42259. this._storedPosition = this.position.clone();
  42260. this._storedRotation = this.rotation.clone();
  42261. if (this.rotationQuaternion) {
  42262. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42263. }
  42264. return _super.prototype.storeState.call(this);
  42265. };
  42266. /**
  42267. * Restored camera state. You must call storeState() first
  42268. */
  42269. TargetCamera.prototype._restoreStateValues = function () {
  42270. if (!_super.prototype._restoreStateValues.call(this)) {
  42271. return false;
  42272. }
  42273. this.position = this._storedPosition.clone();
  42274. this.rotation = this._storedRotation.clone();
  42275. if (this.rotationQuaternion) {
  42276. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42277. }
  42278. this.cameraDirection.copyFromFloats(0, 0, 0);
  42279. this.cameraRotation.copyFromFloats(0, 0);
  42280. return true;
  42281. };
  42282. // Cache
  42283. TargetCamera.prototype._initCache = function () {
  42284. _super.prototype._initCache.call(this);
  42285. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42286. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42287. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42288. };
  42289. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42290. if (!ignoreParentClass) {
  42291. _super.prototype._updateCache.call(this);
  42292. }
  42293. var lockedTargetPosition = this._getLockedTargetPosition();
  42294. if (!lockedTargetPosition) {
  42295. this._cache.lockedTarget = null;
  42296. }
  42297. else {
  42298. if (!this._cache.lockedTarget) {
  42299. this._cache.lockedTarget = lockedTargetPosition.clone();
  42300. }
  42301. else {
  42302. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42303. }
  42304. }
  42305. this._cache.rotation.copyFrom(this.rotation);
  42306. if (this.rotationQuaternion)
  42307. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42308. };
  42309. // Synchronized
  42310. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42311. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42312. return false;
  42313. }
  42314. var lockedTargetPosition = this._getLockedTargetPosition();
  42315. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42316. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42317. };
  42318. // Methods
  42319. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42320. var engine = this.getEngine();
  42321. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42322. };
  42323. // Target
  42324. TargetCamera.prototype.setTarget = function (target) {
  42325. this.upVector.normalize();
  42326. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42327. this._camMatrix.invert();
  42328. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42329. var vDir = target.subtract(this.position);
  42330. if (vDir.x >= 0.0) {
  42331. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42332. }
  42333. else {
  42334. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42335. }
  42336. this.rotation.z = 0;
  42337. if (isNaN(this.rotation.x)) {
  42338. this.rotation.x = 0;
  42339. }
  42340. if (isNaN(this.rotation.y)) {
  42341. this.rotation.y = 0;
  42342. }
  42343. if (isNaN(this.rotation.z)) {
  42344. this.rotation.z = 0;
  42345. }
  42346. if (this.rotationQuaternion) {
  42347. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42348. }
  42349. };
  42350. /**
  42351. * Return the current target position of the camera. This value is expressed in local space.
  42352. */
  42353. TargetCamera.prototype.getTarget = function () {
  42354. return this._currentTarget;
  42355. };
  42356. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42357. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42358. };
  42359. TargetCamera.prototype._updatePosition = function () {
  42360. if (this.parent) {
  42361. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42362. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42363. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42364. return;
  42365. }
  42366. this.position.addInPlace(this.cameraDirection);
  42367. };
  42368. TargetCamera.prototype._checkInputs = function () {
  42369. var needToMove = this._decideIfNeedsToMove();
  42370. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42371. // Move
  42372. if (needToMove) {
  42373. this._updatePosition();
  42374. }
  42375. // Rotate
  42376. if (needToRotate) {
  42377. this.rotation.x += this.cameraRotation.x;
  42378. this.rotation.y += this.cameraRotation.y;
  42379. //rotate, if quaternion is set and rotation was used
  42380. if (this.rotationQuaternion) {
  42381. var len = this.rotation.lengthSquared();
  42382. if (len) {
  42383. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42384. }
  42385. }
  42386. if (!this.noRotationConstraint) {
  42387. var limit = (Math.PI / 2) * 0.95;
  42388. if (this.rotation.x > limit)
  42389. this.rotation.x = limit;
  42390. if (this.rotation.x < -limit)
  42391. this.rotation.x = -limit;
  42392. }
  42393. }
  42394. // Inertia
  42395. if (needToMove) {
  42396. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42397. this.cameraDirection.x = 0;
  42398. }
  42399. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42400. this.cameraDirection.y = 0;
  42401. }
  42402. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42403. this.cameraDirection.z = 0;
  42404. }
  42405. this.cameraDirection.scaleInPlace(this.inertia);
  42406. }
  42407. if (needToRotate) {
  42408. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42409. this.cameraRotation.x = 0;
  42410. }
  42411. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42412. this.cameraRotation.y = 0;
  42413. }
  42414. this.cameraRotation.scaleInPlace(this.inertia);
  42415. }
  42416. _super.prototype._checkInputs.call(this);
  42417. };
  42418. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42419. if (this.rotationQuaternion) {
  42420. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42421. }
  42422. else {
  42423. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42424. }
  42425. //update the up vector!
  42426. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42427. };
  42428. TargetCamera.prototype._getViewMatrix = function () {
  42429. if (this.lockedTarget) {
  42430. this.setTarget(this._getLockedTargetPosition());
  42431. }
  42432. // Compute
  42433. this._updateCameraRotationMatrix();
  42434. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42435. // Computing target and final matrix
  42436. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42437. if (this.getScene().useRightHandedSystem) {
  42438. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42439. }
  42440. else {
  42441. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42442. }
  42443. return this._viewMatrix;
  42444. };
  42445. /**
  42446. * @override
  42447. * Override Camera.createRigCamera
  42448. */
  42449. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42450. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42451. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42452. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42453. if (!this.rotationQuaternion) {
  42454. this.rotationQuaternion = new BABYLON.Quaternion();
  42455. }
  42456. rigCamera._cameraRigParams = {};
  42457. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42458. }
  42459. return rigCamera;
  42460. }
  42461. return null;
  42462. };
  42463. /**
  42464. * @override
  42465. * Override Camera._updateRigCameras
  42466. */
  42467. TargetCamera.prototype._updateRigCameras = function () {
  42468. var camLeft = this._rigCameras[0];
  42469. var camRight = this._rigCameras[1];
  42470. switch (this.cameraRigMode) {
  42471. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42472. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42473. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42474. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42475. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42476. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42477. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42478. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42479. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42480. camLeft.setTarget(this.getTarget());
  42481. camRight.setTarget(this.getTarget());
  42482. break;
  42483. case BABYLON.Camera.RIG_MODE_VR:
  42484. if (camLeft.rotationQuaternion) {
  42485. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42486. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42487. }
  42488. else {
  42489. camLeft.rotation.copyFrom(this.rotation);
  42490. camRight.rotation.copyFrom(this.rotation);
  42491. }
  42492. camLeft.position.copyFrom(this.position);
  42493. camRight.position.copyFrom(this.position);
  42494. break;
  42495. }
  42496. _super.prototype._updateRigCameras.call(this);
  42497. };
  42498. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42499. if (!this._rigCamTransformMatrix) {
  42500. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42501. }
  42502. var target = this.getTarget();
  42503. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42504. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42505. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42506. };
  42507. TargetCamera.prototype.getClassName = function () {
  42508. return "TargetCamera";
  42509. };
  42510. __decorate([
  42511. BABYLON.serializeAsVector3()
  42512. ], TargetCamera.prototype, "rotation", void 0);
  42513. __decorate([
  42514. BABYLON.serialize()
  42515. ], TargetCamera.prototype, "speed", void 0);
  42516. __decorate([
  42517. BABYLON.serializeAsMeshReference("lockedTargetId")
  42518. ], TargetCamera.prototype, "lockedTarget", void 0);
  42519. return TargetCamera;
  42520. }(BABYLON.Camera));
  42521. BABYLON.TargetCamera = TargetCamera;
  42522. })(BABYLON || (BABYLON = {}));
  42523. //# sourceMappingURL=babylon.targetCamera.js.map
  42524. var BABYLON;
  42525. (function (BABYLON) {
  42526. var FreeCameraMouseInput = /** @class */ (function () {
  42527. function FreeCameraMouseInput(touchEnabled) {
  42528. if (touchEnabled === void 0) { touchEnabled = true; }
  42529. this.touchEnabled = touchEnabled;
  42530. this.buttons = [0, 1, 2];
  42531. this.angularSensibility = 2000.0;
  42532. this.previousPosition = null;
  42533. }
  42534. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42535. var _this = this;
  42536. var engine = this.camera.getEngine();
  42537. if (!this._pointerInput) {
  42538. this._pointerInput = function (p, s) {
  42539. var evt = p.event;
  42540. if (engine.isInVRExclusivePointerMode) {
  42541. return;
  42542. }
  42543. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42544. return;
  42545. }
  42546. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42547. return;
  42548. }
  42549. var srcElement = (evt.srcElement || evt.target);
  42550. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42551. try {
  42552. srcElement.setPointerCapture(evt.pointerId);
  42553. }
  42554. catch (e) {
  42555. //Nothing to do with the error. Execution will continue.
  42556. }
  42557. _this.previousPosition = {
  42558. x: evt.clientX,
  42559. y: evt.clientY
  42560. };
  42561. if (!noPreventDefault) {
  42562. evt.preventDefault();
  42563. element.focus();
  42564. }
  42565. }
  42566. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42567. try {
  42568. srcElement.releasePointerCapture(evt.pointerId);
  42569. }
  42570. catch (e) {
  42571. //Nothing to do with the error.
  42572. }
  42573. _this.previousPosition = null;
  42574. if (!noPreventDefault) {
  42575. evt.preventDefault();
  42576. }
  42577. }
  42578. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42579. if (!_this.previousPosition || engine.isPointerLock) {
  42580. return;
  42581. }
  42582. var offsetX = evt.clientX - _this.previousPosition.x;
  42583. var offsetY = evt.clientY - _this.previousPosition.y;
  42584. if (_this.camera.getScene().useRightHandedSystem) {
  42585. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42586. }
  42587. else {
  42588. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42589. }
  42590. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42591. _this.previousPosition = {
  42592. x: evt.clientX,
  42593. y: evt.clientY
  42594. };
  42595. if (!noPreventDefault) {
  42596. evt.preventDefault();
  42597. }
  42598. }
  42599. };
  42600. }
  42601. this._onMouseMove = function (evt) {
  42602. if (!engine.isPointerLock) {
  42603. return;
  42604. }
  42605. if (engine.isInVRExclusivePointerMode) {
  42606. return;
  42607. }
  42608. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42609. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42610. if (_this.camera.getScene().useRightHandedSystem) {
  42611. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42612. }
  42613. else {
  42614. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42615. }
  42616. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42617. _this.previousPosition = null;
  42618. if (!noPreventDefault) {
  42619. evt.preventDefault();
  42620. }
  42621. };
  42622. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  42623. element.addEventListener("mousemove", this._onMouseMove, false);
  42624. };
  42625. FreeCameraMouseInput.prototype.detachControl = function (element) {
  42626. if (this._observer && element) {
  42627. this.camera.getScene().onPointerObservable.remove(this._observer);
  42628. if (this._onMouseMove) {
  42629. element.removeEventListener("mousemove", this._onMouseMove);
  42630. }
  42631. this._observer = null;
  42632. this._onMouseMove = null;
  42633. this.previousPosition = null;
  42634. }
  42635. };
  42636. FreeCameraMouseInput.prototype.getClassName = function () {
  42637. return "FreeCameraMouseInput";
  42638. };
  42639. FreeCameraMouseInput.prototype.getSimpleName = function () {
  42640. return "mouse";
  42641. };
  42642. __decorate([
  42643. BABYLON.serialize()
  42644. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  42645. __decorate([
  42646. BABYLON.serialize()
  42647. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  42648. return FreeCameraMouseInput;
  42649. }());
  42650. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  42651. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  42652. })(BABYLON || (BABYLON = {}));
  42653. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  42654. var BABYLON;
  42655. (function (BABYLON) {
  42656. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  42657. function FreeCameraKeyboardMoveInput() {
  42658. this._keys = new Array();
  42659. this.keysUp = [38];
  42660. this.keysDown = [40];
  42661. this.keysLeft = [37];
  42662. this.keysRight = [39];
  42663. }
  42664. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42665. var _this = this;
  42666. if (this._onCanvasBlurObserver) {
  42667. return;
  42668. }
  42669. this._scene = this.camera.getScene();
  42670. this._engine = this._scene.getEngine();
  42671. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42672. _this._keys = [];
  42673. });
  42674. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42675. var evt = info.event;
  42676. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42677. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42678. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42679. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42680. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42681. var index = _this._keys.indexOf(evt.keyCode);
  42682. if (index === -1) {
  42683. _this._keys.push(evt.keyCode);
  42684. }
  42685. if (!noPreventDefault) {
  42686. evt.preventDefault();
  42687. }
  42688. }
  42689. }
  42690. else {
  42691. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42692. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42693. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42694. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42695. var index = _this._keys.indexOf(evt.keyCode);
  42696. if (index >= 0) {
  42697. _this._keys.splice(index, 1);
  42698. }
  42699. if (!noPreventDefault) {
  42700. evt.preventDefault();
  42701. }
  42702. }
  42703. }
  42704. });
  42705. };
  42706. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  42707. if (this._scene) {
  42708. if (this._onKeyboardObserver) {
  42709. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  42710. }
  42711. if (this._onCanvasBlurObserver) {
  42712. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  42713. }
  42714. this._onKeyboardObserver = null;
  42715. this._onCanvasBlurObserver = null;
  42716. }
  42717. this._keys = [];
  42718. };
  42719. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  42720. if (this._onKeyboardObserver) {
  42721. var camera = this.camera;
  42722. // Keyboard
  42723. for (var index = 0; index < this._keys.length; index++) {
  42724. var keyCode = this._keys[index];
  42725. var speed = camera._computeLocalCameraSpeed();
  42726. if (this.keysLeft.indexOf(keyCode) !== -1) {
  42727. camera._localDirection.copyFromFloats(-speed, 0, 0);
  42728. }
  42729. else if (this.keysUp.indexOf(keyCode) !== -1) {
  42730. camera._localDirection.copyFromFloats(0, 0, speed);
  42731. }
  42732. else if (this.keysRight.indexOf(keyCode) !== -1) {
  42733. camera._localDirection.copyFromFloats(speed, 0, 0);
  42734. }
  42735. else if (this.keysDown.indexOf(keyCode) !== -1) {
  42736. camera._localDirection.copyFromFloats(0, 0, -speed);
  42737. }
  42738. if (camera.getScene().useRightHandedSystem) {
  42739. camera._localDirection.z *= -1;
  42740. }
  42741. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  42742. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  42743. camera.cameraDirection.addInPlace(camera._transformedDirection);
  42744. }
  42745. }
  42746. };
  42747. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  42748. return "FreeCameraKeyboardMoveInput";
  42749. };
  42750. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  42751. this._keys = [];
  42752. };
  42753. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  42754. return "keyboard";
  42755. };
  42756. __decorate([
  42757. BABYLON.serialize()
  42758. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  42759. __decorate([
  42760. BABYLON.serialize()
  42761. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  42762. __decorate([
  42763. BABYLON.serialize()
  42764. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  42765. __decorate([
  42766. BABYLON.serialize()
  42767. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  42768. return FreeCameraKeyboardMoveInput;
  42769. }());
  42770. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  42771. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  42772. })(BABYLON || (BABYLON = {}));
  42773. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  42774. var BABYLON;
  42775. (function (BABYLON) {
  42776. var FreeCameraInputsManager = /** @class */ (function (_super) {
  42777. __extends(FreeCameraInputsManager, _super);
  42778. function FreeCameraInputsManager(camera) {
  42779. return _super.call(this, camera) || this;
  42780. }
  42781. FreeCameraInputsManager.prototype.addKeyboard = function () {
  42782. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  42783. return this;
  42784. };
  42785. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  42786. if (touchEnabled === void 0) { touchEnabled = true; }
  42787. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  42788. return this;
  42789. };
  42790. FreeCameraInputsManager.prototype.addGamepad = function () {
  42791. this.add(new BABYLON.FreeCameraGamepadInput());
  42792. return this;
  42793. };
  42794. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  42795. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  42796. return this;
  42797. };
  42798. FreeCameraInputsManager.prototype.addTouch = function () {
  42799. this.add(new BABYLON.FreeCameraTouchInput());
  42800. return this;
  42801. };
  42802. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  42803. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  42804. return this;
  42805. };
  42806. return FreeCameraInputsManager;
  42807. }(BABYLON.CameraInputsManager));
  42808. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  42809. })(BABYLON || (BABYLON = {}));
  42810. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  42811. var BABYLON;
  42812. (function (BABYLON) {
  42813. var FreeCamera = /** @class */ (function (_super) {
  42814. __extends(FreeCamera, _super);
  42815. function FreeCamera(name, position, scene) {
  42816. var _this = _super.call(this, name, position, scene) || this;
  42817. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  42818. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  42819. _this.checkCollisions = false;
  42820. _this.applyGravity = false;
  42821. _this._needMoveForGravity = false;
  42822. _this._oldPosition = BABYLON.Vector3.Zero();
  42823. _this._diffPosition = BABYLON.Vector3.Zero();
  42824. _this._newPosition = BABYLON.Vector3.Zero();
  42825. // Collisions
  42826. _this._collisionMask = -1;
  42827. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42828. if (collidedMesh === void 0) { collidedMesh = null; }
  42829. //TODO move this to the collision coordinator!
  42830. if (_this.getScene().workerCollisions)
  42831. newPosition.multiplyInPlace(_this._collider._radius);
  42832. var updatePosition = function (newPos) {
  42833. _this._newPosition.copyFrom(newPos);
  42834. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  42835. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  42836. _this.position.addInPlace(_this._diffPosition);
  42837. if (_this.onCollide && collidedMesh) {
  42838. _this.onCollide(collidedMesh);
  42839. }
  42840. }
  42841. };
  42842. updatePosition(newPosition);
  42843. };
  42844. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  42845. _this.inputs.addKeyboard().addMouse();
  42846. return _this;
  42847. }
  42848. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  42849. //-- begin properties for backward compatibility for inputs
  42850. /**
  42851. * Gets the input sensibility for a mouse input. (default is 2000.0)
  42852. * Higher values reduce sensitivity.
  42853. */
  42854. get: function () {
  42855. var mouse = this.inputs.attached["mouse"];
  42856. if (mouse)
  42857. return mouse.angularSensibility;
  42858. return 0;
  42859. },
  42860. /**
  42861. * Sets the input sensibility for a mouse input. (default is 2000.0)
  42862. * Higher values reduce sensitivity.
  42863. */
  42864. set: function (value) {
  42865. var mouse = this.inputs.attached["mouse"];
  42866. if (mouse)
  42867. mouse.angularSensibility = value;
  42868. },
  42869. enumerable: true,
  42870. configurable: true
  42871. });
  42872. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  42873. get: function () {
  42874. var keyboard = this.inputs.attached["keyboard"];
  42875. if (keyboard)
  42876. return keyboard.keysUp;
  42877. return [];
  42878. },
  42879. set: function (value) {
  42880. var keyboard = this.inputs.attached["keyboard"];
  42881. if (keyboard)
  42882. keyboard.keysUp = value;
  42883. },
  42884. enumerable: true,
  42885. configurable: true
  42886. });
  42887. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  42888. get: function () {
  42889. var keyboard = this.inputs.attached["keyboard"];
  42890. if (keyboard)
  42891. return keyboard.keysDown;
  42892. return [];
  42893. },
  42894. set: function (value) {
  42895. var keyboard = this.inputs.attached["keyboard"];
  42896. if (keyboard)
  42897. keyboard.keysDown = value;
  42898. },
  42899. enumerable: true,
  42900. configurable: true
  42901. });
  42902. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  42903. get: function () {
  42904. var keyboard = this.inputs.attached["keyboard"];
  42905. if (keyboard)
  42906. return keyboard.keysLeft;
  42907. return [];
  42908. },
  42909. set: function (value) {
  42910. var keyboard = this.inputs.attached["keyboard"];
  42911. if (keyboard)
  42912. keyboard.keysLeft = value;
  42913. },
  42914. enumerable: true,
  42915. configurable: true
  42916. });
  42917. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  42918. get: function () {
  42919. var keyboard = this.inputs.attached["keyboard"];
  42920. if (keyboard)
  42921. return keyboard.keysRight;
  42922. return [];
  42923. },
  42924. set: function (value) {
  42925. var keyboard = this.inputs.attached["keyboard"];
  42926. if (keyboard)
  42927. keyboard.keysRight = value;
  42928. },
  42929. enumerable: true,
  42930. configurable: true
  42931. });
  42932. // Controls
  42933. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  42934. this.inputs.attachElement(element, noPreventDefault);
  42935. };
  42936. FreeCamera.prototype.detachControl = function (element) {
  42937. this.inputs.detachElement(element);
  42938. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42939. this.cameraRotation = new BABYLON.Vector2(0, 0);
  42940. };
  42941. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  42942. get: function () {
  42943. return this._collisionMask;
  42944. },
  42945. set: function (mask) {
  42946. this._collisionMask = !isNaN(mask) ? mask : -1;
  42947. },
  42948. enumerable: true,
  42949. configurable: true
  42950. });
  42951. FreeCamera.prototype._collideWithWorld = function (displacement) {
  42952. var globalPosition;
  42953. if (this.parent) {
  42954. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  42955. }
  42956. else {
  42957. globalPosition = this.position;
  42958. }
  42959. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  42960. this._oldPosition.addInPlace(this.ellipsoidOffset);
  42961. if (!this._collider) {
  42962. this._collider = new BABYLON.Collider();
  42963. }
  42964. this._collider._radius = this.ellipsoid;
  42965. this._collider.collisionMask = this._collisionMask;
  42966. //no need for clone, as long as gravity is not on.
  42967. var actualDisplacement = displacement;
  42968. //add gravity to the direction to prevent the dual-collision checking
  42969. if (this.applyGravity) {
  42970. //this prevents mending with cameraDirection, a global variable of the free camera class.
  42971. actualDisplacement = displacement.add(this.getScene().gravity);
  42972. }
  42973. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42974. };
  42975. FreeCamera.prototype._checkInputs = function () {
  42976. if (!this._localDirection) {
  42977. this._localDirection = BABYLON.Vector3.Zero();
  42978. this._transformedDirection = BABYLON.Vector3.Zero();
  42979. }
  42980. this.inputs.checkInputs();
  42981. _super.prototype._checkInputs.call(this);
  42982. };
  42983. FreeCamera.prototype._decideIfNeedsToMove = function () {
  42984. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42985. };
  42986. FreeCamera.prototype._updatePosition = function () {
  42987. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  42988. this._collideWithWorld(this.cameraDirection);
  42989. }
  42990. else {
  42991. _super.prototype._updatePosition.call(this);
  42992. }
  42993. };
  42994. FreeCamera.prototype.dispose = function () {
  42995. this.inputs.clear();
  42996. _super.prototype.dispose.call(this);
  42997. };
  42998. FreeCamera.prototype.getClassName = function () {
  42999. return "FreeCamera";
  43000. };
  43001. __decorate([
  43002. BABYLON.serializeAsVector3()
  43003. ], FreeCamera.prototype, "ellipsoid", void 0);
  43004. __decorate([
  43005. BABYLON.serializeAsVector3()
  43006. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43007. __decorate([
  43008. BABYLON.serialize()
  43009. ], FreeCamera.prototype, "checkCollisions", void 0);
  43010. __decorate([
  43011. BABYLON.serialize()
  43012. ], FreeCamera.prototype, "applyGravity", void 0);
  43013. return FreeCamera;
  43014. }(BABYLON.TargetCamera));
  43015. BABYLON.FreeCamera = FreeCamera;
  43016. })(BABYLON || (BABYLON = {}));
  43017. //# sourceMappingURL=babylon.freeCamera.js.map
  43018. var BABYLON;
  43019. (function (BABYLON) {
  43020. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43021. function ArcRotateCameraKeyboardMoveInput() {
  43022. this._keys = new Array();
  43023. this.keysUp = [38];
  43024. this.keysDown = [40];
  43025. this.keysLeft = [37];
  43026. this.keysRight = [39];
  43027. this.keysReset = [220];
  43028. this.panningSensibility = 50.0;
  43029. this.zoomingSensibility = 25.0;
  43030. this.useAltToZoom = true;
  43031. }
  43032. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43033. var _this = this;
  43034. if (this._onCanvasBlurObserver) {
  43035. return;
  43036. }
  43037. this._scene = this.camera.getScene();
  43038. this._engine = this._scene.getEngine();
  43039. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43040. _this._keys = [];
  43041. });
  43042. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43043. var evt = info.event;
  43044. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43045. _this._ctrlPressed = evt.ctrlKey;
  43046. _this._altPressed = evt.altKey;
  43047. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43048. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43049. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43050. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43051. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43052. var index = _this._keys.indexOf(evt.keyCode);
  43053. if (index === -1) {
  43054. _this._keys.push(evt.keyCode);
  43055. }
  43056. if (evt.preventDefault) {
  43057. if (!noPreventDefault) {
  43058. evt.preventDefault();
  43059. }
  43060. }
  43061. }
  43062. }
  43063. else {
  43064. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43065. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43066. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43067. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43068. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43069. var index = _this._keys.indexOf(evt.keyCode);
  43070. if (index >= 0) {
  43071. _this._keys.splice(index, 1);
  43072. }
  43073. if (evt.preventDefault) {
  43074. if (!noPreventDefault) {
  43075. evt.preventDefault();
  43076. }
  43077. }
  43078. }
  43079. }
  43080. });
  43081. };
  43082. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43083. if (this._scene) {
  43084. if (this._onKeyboardObserver) {
  43085. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43086. }
  43087. if (this._onCanvasBlurObserver) {
  43088. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43089. }
  43090. this._onKeyboardObserver = null;
  43091. this._onCanvasBlurObserver = null;
  43092. }
  43093. this._keys = [];
  43094. };
  43095. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43096. if (this._onKeyboardObserver) {
  43097. var camera = this.camera;
  43098. for (var index = 0; index < this._keys.length; index++) {
  43099. var keyCode = this._keys[index];
  43100. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43101. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43102. camera.inertialPanningX -= 1 / this.panningSensibility;
  43103. }
  43104. else {
  43105. camera.inertialAlphaOffset -= 0.01;
  43106. }
  43107. }
  43108. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43109. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43110. camera.inertialPanningY += 1 / this.panningSensibility;
  43111. }
  43112. else if (this._altPressed && this.useAltToZoom) {
  43113. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43114. }
  43115. else {
  43116. camera.inertialBetaOffset -= 0.01;
  43117. }
  43118. }
  43119. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43120. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43121. camera.inertialPanningX += 1 / this.panningSensibility;
  43122. }
  43123. else {
  43124. camera.inertialAlphaOffset += 0.01;
  43125. }
  43126. }
  43127. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43128. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43129. camera.inertialPanningY -= 1 / this.panningSensibility;
  43130. }
  43131. else if (this._altPressed && this.useAltToZoom) {
  43132. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43133. }
  43134. else {
  43135. camera.inertialBetaOffset += 0.01;
  43136. }
  43137. }
  43138. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43139. camera.restoreState();
  43140. }
  43141. }
  43142. }
  43143. };
  43144. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43145. return "ArcRotateCameraKeyboardMoveInput";
  43146. };
  43147. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43148. return "keyboard";
  43149. };
  43150. __decorate([
  43151. BABYLON.serialize()
  43152. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43153. __decorate([
  43154. BABYLON.serialize()
  43155. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43156. __decorate([
  43157. BABYLON.serialize()
  43158. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43159. __decorate([
  43160. BABYLON.serialize()
  43161. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43162. __decorate([
  43163. BABYLON.serialize()
  43164. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43165. __decorate([
  43166. BABYLON.serialize()
  43167. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43168. __decorate([
  43169. BABYLON.serialize()
  43170. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43171. __decorate([
  43172. BABYLON.serialize()
  43173. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43174. return ArcRotateCameraKeyboardMoveInput;
  43175. }());
  43176. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43177. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43178. })(BABYLON || (BABYLON = {}));
  43179. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43180. var BABYLON;
  43181. (function (BABYLON) {
  43182. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43183. function ArcRotateCameraMouseWheelInput() {
  43184. this.wheelPrecision = 3.0;
  43185. /**
  43186. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43187. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43188. */
  43189. this.wheelDeltaPercentage = 0;
  43190. }
  43191. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43192. var _this = this;
  43193. this._wheel = function (p, s) {
  43194. //sanity check - this should be a PointerWheel event.
  43195. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43196. return;
  43197. var event = p.event;
  43198. var delta = 0;
  43199. if (event.wheelDelta) {
  43200. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43201. }
  43202. else if (event.detail) {
  43203. delta = -event.detail / _this.wheelPrecision;
  43204. }
  43205. if (delta)
  43206. _this.camera.inertialRadiusOffset += delta;
  43207. if (event.preventDefault) {
  43208. if (!noPreventDefault) {
  43209. event.preventDefault();
  43210. }
  43211. }
  43212. };
  43213. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43214. };
  43215. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43216. if (this._observer && element) {
  43217. this.camera.getScene().onPointerObservable.remove(this._observer);
  43218. this._observer = null;
  43219. this._wheel = null;
  43220. }
  43221. };
  43222. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43223. return "ArcRotateCameraMouseWheelInput";
  43224. };
  43225. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43226. return "mousewheel";
  43227. };
  43228. __decorate([
  43229. BABYLON.serialize()
  43230. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43231. __decorate([
  43232. BABYLON.serialize()
  43233. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43234. return ArcRotateCameraMouseWheelInput;
  43235. }());
  43236. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43237. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43238. })(BABYLON || (BABYLON = {}));
  43239. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43240. var BABYLON;
  43241. (function (BABYLON) {
  43242. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43243. function ArcRotateCameraPointersInput() {
  43244. this.buttons = [0, 1, 2];
  43245. this.angularSensibilityX = 1000.0;
  43246. this.angularSensibilityY = 1000.0;
  43247. this.pinchPrecision = 12.0;
  43248. /**
  43249. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43250. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43251. */
  43252. this.pinchDeltaPercentage = 0;
  43253. this.panningSensibility = 1000.0;
  43254. this.multiTouchPanning = true;
  43255. this.multiTouchPanAndZoom = true;
  43256. this._isPanClick = false;
  43257. this.pinchInwards = true;
  43258. }
  43259. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43260. var _this = this;
  43261. var engine = this.camera.getEngine();
  43262. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43263. var pointA = null;
  43264. var pointB = null;
  43265. var previousPinchSquaredDistance = 0;
  43266. var initialDistance = 0;
  43267. var twoFingerActivityCount = 0;
  43268. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43269. this._pointerInput = function (p, s) {
  43270. var evt = p.event;
  43271. var isTouch = p.event.pointerType === "touch";
  43272. if (engine.isInVRExclusivePointerMode) {
  43273. return;
  43274. }
  43275. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43276. return;
  43277. }
  43278. var srcElement = (evt.srcElement || evt.target);
  43279. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43280. try {
  43281. srcElement.setPointerCapture(evt.pointerId);
  43282. }
  43283. catch (e) {
  43284. //Nothing to do with the error. Execution will continue.
  43285. }
  43286. // Manage panning with pan button click
  43287. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43288. // manage pointers
  43289. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43290. if (pointA === null) {
  43291. pointA = cacheSoloPointer;
  43292. }
  43293. else if (pointB === null) {
  43294. pointB = cacheSoloPointer;
  43295. }
  43296. if (!noPreventDefault) {
  43297. evt.preventDefault();
  43298. element.focus();
  43299. }
  43300. }
  43301. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43302. _this.camera.restoreState();
  43303. }
  43304. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43305. try {
  43306. srcElement.releasePointerCapture(evt.pointerId);
  43307. }
  43308. catch (e) {
  43309. //Nothing to do with the error.
  43310. }
  43311. cacheSoloPointer = null;
  43312. previousPinchSquaredDistance = 0;
  43313. previousMultiTouchPanPosition.isPaning = false;
  43314. previousMultiTouchPanPosition.isPinching = false;
  43315. twoFingerActivityCount = 0;
  43316. initialDistance = 0;
  43317. if (!isTouch) {
  43318. pointB = null; // Mouse and pen are mono pointer
  43319. }
  43320. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43321. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43322. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43323. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43324. if (engine.badOS) {
  43325. pointA = pointB = null;
  43326. }
  43327. else {
  43328. //only remove the impacted pointer in case of multitouch allowing on most
  43329. //platforms switching from rotate to zoom and pan seamlessly.
  43330. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43331. pointA = pointB;
  43332. pointB = null;
  43333. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43334. }
  43335. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43336. pointB = null;
  43337. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43338. }
  43339. else {
  43340. pointA = pointB = null;
  43341. }
  43342. }
  43343. if (!noPreventDefault) {
  43344. evt.preventDefault();
  43345. }
  43346. }
  43347. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43348. if (!noPreventDefault) {
  43349. evt.preventDefault();
  43350. }
  43351. // One button down
  43352. if (pointA && pointB === null && cacheSoloPointer) {
  43353. if (_this.panningSensibility !== 0 &&
  43354. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43355. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43356. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43357. }
  43358. else {
  43359. var offsetX = evt.clientX - cacheSoloPointer.x;
  43360. var offsetY = evt.clientY - cacheSoloPointer.y;
  43361. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43362. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43363. }
  43364. cacheSoloPointer.x = evt.clientX;
  43365. cacheSoloPointer.y = evt.clientY;
  43366. }
  43367. else if (pointA && pointB) {
  43368. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43369. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43370. ed.x = evt.clientX;
  43371. ed.y = evt.clientY;
  43372. var direction = _this.pinchInwards ? 1 : -1;
  43373. var distX = pointA.x - pointB.x;
  43374. var distY = pointA.y - pointB.y;
  43375. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43376. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43377. if (previousPinchSquaredDistance === 0) {
  43378. initialDistance = pinchDistance;
  43379. previousPinchSquaredDistance = pinchSquaredDistance;
  43380. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43381. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43382. return;
  43383. }
  43384. if (_this.multiTouchPanAndZoom) {
  43385. if (_this.pinchDeltaPercentage) {
  43386. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43387. }
  43388. else {
  43389. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43390. (_this.pinchPrecision *
  43391. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43392. direction);
  43393. }
  43394. if (_this.panningSensibility !== 0) {
  43395. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43396. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43397. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43398. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43399. previousMultiTouchPanPosition.x = pointersCenterX;
  43400. previousMultiTouchPanPosition.y = pointersCenterY;
  43401. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43402. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43403. }
  43404. }
  43405. else {
  43406. twoFingerActivityCount++;
  43407. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43408. if (_this.pinchDeltaPercentage) {
  43409. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43410. }
  43411. else {
  43412. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43413. (_this.pinchPrecision *
  43414. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43415. direction);
  43416. }
  43417. previousMultiTouchPanPosition.isPaning = false;
  43418. previousMultiTouchPanPosition.isPinching = true;
  43419. }
  43420. else {
  43421. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43422. if (!previousMultiTouchPanPosition.isPaning) {
  43423. previousMultiTouchPanPosition.isPaning = true;
  43424. previousMultiTouchPanPosition.isPinching = false;
  43425. previousMultiTouchPanPosition.x = ed.x;
  43426. previousMultiTouchPanPosition.y = ed.y;
  43427. return;
  43428. }
  43429. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43430. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43431. }
  43432. }
  43433. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43434. previousMultiTouchPanPosition.x = ed.x;
  43435. previousMultiTouchPanPosition.y = ed.y;
  43436. }
  43437. }
  43438. previousPinchSquaredDistance = pinchSquaredDistance;
  43439. }
  43440. }
  43441. };
  43442. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43443. this._onContextMenu = function (evt) {
  43444. evt.preventDefault();
  43445. };
  43446. if (!this.camera._useCtrlForPanning) {
  43447. element.addEventListener("contextmenu", this._onContextMenu, false);
  43448. }
  43449. this._onLostFocus = function () {
  43450. //this._keys = [];
  43451. pointA = pointB = null;
  43452. previousPinchSquaredDistance = 0;
  43453. previousMultiTouchPanPosition.isPaning = false;
  43454. previousMultiTouchPanPosition.isPinching = false;
  43455. twoFingerActivityCount = 0;
  43456. cacheSoloPointer = null;
  43457. initialDistance = 0;
  43458. };
  43459. this._onMouseMove = function (evt) {
  43460. if (!engine.isPointerLock) {
  43461. return;
  43462. }
  43463. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43464. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43465. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43466. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43467. if (!noPreventDefault) {
  43468. evt.preventDefault();
  43469. }
  43470. };
  43471. this._onGestureStart = function (e) {
  43472. if (window.MSGesture === undefined) {
  43473. return;
  43474. }
  43475. if (!_this._MSGestureHandler) {
  43476. _this._MSGestureHandler = new MSGesture();
  43477. _this._MSGestureHandler.target = element;
  43478. }
  43479. _this._MSGestureHandler.addPointer(e.pointerId);
  43480. };
  43481. this._onGesture = function (e) {
  43482. _this.camera.radius *= e.scale;
  43483. if (e.preventDefault) {
  43484. if (!noPreventDefault) {
  43485. e.stopPropagation();
  43486. e.preventDefault();
  43487. }
  43488. }
  43489. };
  43490. element.addEventListener("mousemove", this._onMouseMove, false);
  43491. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43492. element.addEventListener("MSGestureChange", this._onGesture, false);
  43493. BABYLON.Tools.RegisterTopRootEvents([
  43494. { name: "blur", handler: this._onLostFocus }
  43495. ]);
  43496. };
  43497. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43498. if (this._onLostFocus) {
  43499. BABYLON.Tools.UnregisterTopRootEvents([
  43500. { name: "blur", handler: this._onLostFocus }
  43501. ]);
  43502. }
  43503. if (element && this._observer) {
  43504. this.camera.getScene().onPointerObservable.remove(this._observer);
  43505. this._observer = null;
  43506. if (this._onContextMenu) {
  43507. element.removeEventListener("contextmenu", this._onContextMenu);
  43508. }
  43509. if (this._onMouseMove) {
  43510. element.removeEventListener("mousemove", this._onMouseMove);
  43511. }
  43512. if (this._onGestureStart) {
  43513. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43514. }
  43515. if (this._onGesture) {
  43516. element.removeEventListener("MSGestureChange", this._onGesture);
  43517. }
  43518. this._isPanClick = false;
  43519. this.pinchInwards = true;
  43520. this._onMouseMove = null;
  43521. this._onGestureStart = null;
  43522. this._onGesture = null;
  43523. this._MSGestureHandler = null;
  43524. this._onLostFocus = null;
  43525. this._onContextMenu = null;
  43526. }
  43527. };
  43528. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43529. return "ArcRotateCameraPointersInput";
  43530. };
  43531. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43532. return "pointers";
  43533. };
  43534. __decorate([
  43535. BABYLON.serialize()
  43536. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43537. __decorate([
  43538. BABYLON.serialize()
  43539. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43540. __decorate([
  43541. BABYLON.serialize()
  43542. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43543. __decorate([
  43544. BABYLON.serialize()
  43545. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43546. __decorate([
  43547. BABYLON.serialize()
  43548. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43549. __decorate([
  43550. BABYLON.serialize()
  43551. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43552. __decorate([
  43553. BABYLON.serialize()
  43554. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43555. __decorate([
  43556. BABYLON.serialize()
  43557. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43558. return ArcRotateCameraPointersInput;
  43559. }());
  43560. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43561. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43562. })(BABYLON || (BABYLON = {}));
  43563. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43564. var BABYLON;
  43565. (function (BABYLON) {
  43566. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43567. __extends(ArcRotateCameraInputsManager, _super);
  43568. function ArcRotateCameraInputsManager(camera) {
  43569. return _super.call(this, camera) || this;
  43570. }
  43571. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43572. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43573. return this;
  43574. };
  43575. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43576. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43577. return this;
  43578. };
  43579. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43580. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43581. return this;
  43582. };
  43583. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43584. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43585. return this;
  43586. };
  43587. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43588. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43589. return this;
  43590. };
  43591. return ArcRotateCameraInputsManager;
  43592. }(BABYLON.CameraInputsManager));
  43593. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43594. })(BABYLON || (BABYLON = {}));
  43595. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43596. var BABYLON;
  43597. (function (BABYLON) {
  43598. var ArcRotateCamera = /** @class */ (function (_super) {
  43599. __extends(ArcRotateCamera, _super);
  43600. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43601. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43602. _this.inertialAlphaOffset = 0;
  43603. _this.inertialBetaOffset = 0;
  43604. _this.inertialRadiusOffset = 0;
  43605. _this.lowerAlphaLimit = null;
  43606. _this.upperAlphaLimit = null;
  43607. _this.lowerBetaLimit = 0.01;
  43608. _this.upperBetaLimit = Math.PI;
  43609. _this.lowerRadiusLimit = null;
  43610. _this.upperRadiusLimit = null;
  43611. _this.inertialPanningX = 0;
  43612. _this.inertialPanningY = 0;
  43613. _this.pinchToPanMaxDistance = 20;
  43614. _this.panningDistanceLimit = null;
  43615. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  43616. _this.panningInertia = 0.9;
  43617. //-- end properties for backward compatibility for inputs
  43618. _this.zoomOnFactor = 1;
  43619. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  43620. _this.allowUpsideDown = true;
  43621. _this._viewMatrix = new BABYLON.Matrix();
  43622. // Panning
  43623. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  43624. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  43625. _this.checkCollisions = false;
  43626. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43627. _this._previousPosition = BABYLON.Vector3.Zero();
  43628. _this._collisionVelocity = BABYLON.Vector3.Zero();
  43629. _this._newPosition = BABYLON.Vector3.Zero();
  43630. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43631. if (collidedMesh === void 0) { collidedMesh = null; }
  43632. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  43633. newPosition.multiplyInPlace(_this._collider._radius);
  43634. }
  43635. if (!collidedMesh) {
  43636. _this._previousPosition.copyFrom(_this.position);
  43637. }
  43638. else {
  43639. _this.setPosition(newPosition);
  43640. if (_this.onCollide) {
  43641. _this.onCollide(collidedMesh);
  43642. }
  43643. }
  43644. // Recompute because of constraints
  43645. var cosa = Math.cos(_this.alpha);
  43646. var sina = Math.sin(_this.alpha);
  43647. var cosb = Math.cos(_this.beta);
  43648. var sinb = Math.sin(_this.beta);
  43649. if (sinb === 0) {
  43650. sinb = 0.0001;
  43651. }
  43652. var target = _this._getTargetPosition();
  43653. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  43654. _this.position.copyFrom(_this._newPosition);
  43655. var up = _this.upVector;
  43656. if (_this.allowUpsideDown && _this.beta < 0) {
  43657. up = up.clone();
  43658. up = up.negate();
  43659. }
  43660. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  43661. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  43662. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  43663. _this._collisionTriggered = false;
  43664. };
  43665. _this._target = BABYLON.Vector3.Zero();
  43666. if (target) {
  43667. _this.setTarget(target);
  43668. }
  43669. _this.alpha = alpha;
  43670. _this.beta = beta;
  43671. _this.radius = radius;
  43672. _this.getViewMatrix();
  43673. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  43674. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  43675. return _this;
  43676. }
  43677. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  43678. get: function () {
  43679. return this._target;
  43680. },
  43681. set: function (value) {
  43682. this.setTarget(value);
  43683. },
  43684. enumerable: true,
  43685. configurable: true
  43686. });
  43687. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  43688. //-- begin properties for backward compatibility for inputs
  43689. get: function () {
  43690. var pointers = this.inputs.attached["pointers"];
  43691. if (pointers)
  43692. return pointers.angularSensibilityX;
  43693. return 0;
  43694. },
  43695. set: function (value) {
  43696. var pointers = this.inputs.attached["pointers"];
  43697. if (pointers) {
  43698. pointers.angularSensibilityX = value;
  43699. }
  43700. },
  43701. enumerable: true,
  43702. configurable: true
  43703. });
  43704. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  43705. get: function () {
  43706. var pointers = this.inputs.attached["pointers"];
  43707. if (pointers)
  43708. return pointers.angularSensibilityY;
  43709. return 0;
  43710. },
  43711. set: function (value) {
  43712. var pointers = this.inputs.attached["pointers"];
  43713. if (pointers) {
  43714. pointers.angularSensibilityY = value;
  43715. }
  43716. },
  43717. enumerable: true,
  43718. configurable: true
  43719. });
  43720. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  43721. get: function () {
  43722. var pointers = this.inputs.attached["pointers"];
  43723. if (pointers)
  43724. return pointers.pinchPrecision;
  43725. return 0;
  43726. },
  43727. set: function (value) {
  43728. var pointers = this.inputs.attached["pointers"];
  43729. if (pointers) {
  43730. pointers.pinchPrecision = value;
  43731. }
  43732. },
  43733. enumerable: true,
  43734. configurable: true
  43735. });
  43736. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  43737. get: function () {
  43738. var pointers = this.inputs.attached["pointers"];
  43739. if (pointers)
  43740. return pointers.pinchDeltaPercentage;
  43741. return 0;
  43742. },
  43743. set: function (value) {
  43744. var pointers = this.inputs.attached["pointers"];
  43745. if (pointers) {
  43746. pointers.pinchDeltaPercentage = value;
  43747. }
  43748. },
  43749. enumerable: true,
  43750. configurable: true
  43751. });
  43752. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  43753. get: function () {
  43754. var pointers = this.inputs.attached["pointers"];
  43755. if (pointers)
  43756. return pointers.panningSensibility;
  43757. return 0;
  43758. },
  43759. set: function (value) {
  43760. var pointers = this.inputs.attached["pointers"];
  43761. if (pointers) {
  43762. pointers.panningSensibility = value;
  43763. }
  43764. },
  43765. enumerable: true,
  43766. configurable: true
  43767. });
  43768. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  43769. get: function () {
  43770. var keyboard = this.inputs.attached["keyboard"];
  43771. if (keyboard)
  43772. return keyboard.keysUp;
  43773. return [];
  43774. },
  43775. set: function (value) {
  43776. var keyboard = this.inputs.attached["keyboard"];
  43777. if (keyboard)
  43778. keyboard.keysUp = value;
  43779. },
  43780. enumerable: true,
  43781. configurable: true
  43782. });
  43783. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  43784. get: function () {
  43785. var keyboard = this.inputs.attached["keyboard"];
  43786. if (keyboard)
  43787. return keyboard.keysDown;
  43788. return [];
  43789. },
  43790. set: function (value) {
  43791. var keyboard = this.inputs.attached["keyboard"];
  43792. if (keyboard)
  43793. keyboard.keysDown = value;
  43794. },
  43795. enumerable: true,
  43796. configurable: true
  43797. });
  43798. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  43799. get: function () {
  43800. var keyboard = this.inputs.attached["keyboard"];
  43801. if (keyboard)
  43802. return keyboard.keysLeft;
  43803. return [];
  43804. },
  43805. set: function (value) {
  43806. var keyboard = this.inputs.attached["keyboard"];
  43807. if (keyboard)
  43808. keyboard.keysLeft = value;
  43809. },
  43810. enumerable: true,
  43811. configurable: true
  43812. });
  43813. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  43814. get: function () {
  43815. var keyboard = this.inputs.attached["keyboard"];
  43816. if (keyboard)
  43817. return keyboard.keysRight;
  43818. return [];
  43819. },
  43820. set: function (value) {
  43821. var keyboard = this.inputs.attached["keyboard"];
  43822. if (keyboard)
  43823. keyboard.keysRight = value;
  43824. },
  43825. enumerable: true,
  43826. configurable: true
  43827. });
  43828. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  43829. get: function () {
  43830. var mousewheel = this.inputs.attached["mousewheel"];
  43831. if (mousewheel)
  43832. return mousewheel.wheelPrecision;
  43833. return 0;
  43834. },
  43835. set: function (value) {
  43836. var mousewheel = this.inputs.attached["mousewheel"];
  43837. if (mousewheel)
  43838. mousewheel.wheelPrecision = value;
  43839. },
  43840. enumerable: true,
  43841. configurable: true
  43842. });
  43843. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  43844. get: function () {
  43845. var mousewheel = this.inputs.attached["mousewheel"];
  43846. if (mousewheel)
  43847. return mousewheel.wheelDeltaPercentage;
  43848. return 0;
  43849. },
  43850. set: function (value) {
  43851. var mousewheel = this.inputs.attached["mousewheel"];
  43852. if (mousewheel)
  43853. mousewheel.wheelDeltaPercentage = value;
  43854. },
  43855. enumerable: true,
  43856. configurable: true
  43857. });
  43858. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  43859. get: function () {
  43860. return this._bouncingBehavior;
  43861. },
  43862. enumerable: true,
  43863. configurable: true
  43864. });
  43865. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  43866. get: function () {
  43867. return this._bouncingBehavior != null;
  43868. },
  43869. set: function (value) {
  43870. if (value === this.useBouncingBehavior) {
  43871. return;
  43872. }
  43873. if (value) {
  43874. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  43875. this.addBehavior(this._bouncingBehavior);
  43876. }
  43877. else if (this._bouncingBehavior) {
  43878. this.removeBehavior(this._bouncingBehavior);
  43879. this._bouncingBehavior = null;
  43880. }
  43881. },
  43882. enumerable: true,
  43883. configurable: true
  43884. });
  43885. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  43886. get: function () {
  43887. return this._framingBehavior;
  43888. },
  43889. enumerable: true,
  43890. configurable: true
  43891. });
  43892. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  43893. get: function () {
  43894. return this._framingBehavior != null;
  43895. },
  43896. set: function (value) {
  43897. if (value === this.useFramingBehavior) {
  43898. return;
  43899. }
  43900. if (value) {
  43901. this._framingBehavior = new BABYLON.FramingBehavior();
  43902. this.addBehavior(this._framingBehavior);
  43903. }
  43904. else if (this._framingBehavior) {
  43905. this.removeBehavior(this._framingBehavior);
  43906. this._framingBehavior = null;
  43907. }
  43908. },
  43909. enumerable: true,
  43910. configurable: true
  43911. });
  43912. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  43913. get: function () {
  43914. return this._autoRotationBehavior;
  43915. },
  43916. enumerable: true,
  43917. configurable: true
  43918. });
  43919. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  43920. get: function () {
  43921. return this._autoRotationBehavior != null;
  43922. },
  43923. set: function (value) {
  43924. if (value === this.useAutoRotationBehavior) {
  43925. return;
  43926. }
  43927. if (value) {
  43928. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  43929. this.addBehavior(this._autoRotationBehavior);
  43930. }
  43931. else if (this._autoRotationBehavior) {
  43932. this.removeBehavior(this._autoRotationBehavior);
  43933. this._autoRotationBehavior = null;
  43934. }
  43935. },
  43936. enumerable: true,
  43937. configurable: true
  43938. });
  43939. // Cache
  43940. ArcRotateCamera.prototype._initCache = function () {
  43941. _super.prototype._initCache.call(this);
  43942. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43943. this._cache.alpha = undefined;
  43944. this._cache.beta = undefined;
  43945. this._cache.radius = undefined;
  43946. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  43947. };
  43948. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  43949. if (!ignoreParentClass) {
  43950. _super.prototype._updateCache.call(this);
  43951. }
  43952. this._cache._target.copyFrom(this._getTargetPosition());
  43953. this._cache.alpha = this.alpha;
  43954. this._cache.beta = this.beta;
  43955. this._cache.radius = this.radius;
  43956. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  43957. };
  43958. ArcRotateCamera.prototype._getTargetPosition = function () {
  43959. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  43960. var pos = this._targetHost.getAbsolutePosition();
  43961. if (this._targetBoundingCenter) {
  43962. pos.addToRef(this._targetBoundingCenter, this._target);
  43963. }
  43964. else {
  43965. this._target.copyFrom(pos);
  43966. }
  43967. }
  43968. var lockedTargetPosition = this._getLockedTargetPosition();
  43969. if (lockedTargetPosition) {
  43970. return lockedTargetPosition;
  43971. }
  43972. return this._target;
  43973. };
  43974. ArcRotateCamera.prototype.storeState = function () {
  43975. this._storedAlpha = this.alpha;
  43976. this._storedBeta = this.beta;
  43977. this._storedRadius = this.radius;
  43978. this._storedTarget = this._getTargetPosition().clone();
  43979. return _super.prototype.storeState.call(this);
  43980. };
  43981. /**
  43982. * Restored camera state. You must call storeState() first
  43983. */
  43984. ArcRotateCamera.prototype._restoreStateValues = function () {
  43985. if (!_super.prototype._restoreStateValues.call(this)) {
  43986. return false;
  43987. }
  43988. this.alpha = this._storedAlpha;
  43989. this.beta = this._storedBeta;
  43990. this.radius = this._storedRadius;
  43991. this.setTarget(this._storedTarget.clone());
  43992. this.inertialAlphaOffset = 0;
  43993. this.inertialBetaOffset = 0;
  43994. this.inertialRadiusOffset = 0;
  43995. this.inertialPanningX = 0;
  43996. this.inertialPanningY = 0;
  43997. return true;
  43998. };
  43999. // Synchronized
  44000. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44001. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44002. return false;
  44003. return this._cache._target.equals(this._getTargetPosition())
  44004. && this._cache.alpha === this.alpha
  44005. && this._cache.beta === this.beta
  44006. && this._cache.radius === this.radius
  44007. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44008. };
  44009. // Methods
  44010. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44011. var _this = this;
  44012. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44013. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44014. this._useCtrlForPanning = useCtrlForPanning;
  44015. this._panningMouseButton = panningMouseButton;
  44016. this.inputs.attachElement(element, noPreventDefault);
  44017. this._reset = function () {
  44018. _this.inertialAlphaOffset = 0;
  44019. _this.inertialBetaOffset = 0;
  44020. _this.inertialRadiusOffset = 0;
  44021. _this.inertialPanningX = 0;
  44022. _this.inertialPanningY = 0;
  44023. };
  44024. };
  44025. ArcRotateCamera.prototype.detachControl = function (element) {
  44026. this.inputs.detachElement(element);
  44027. if (this._reset) {
  44028. this._reset();
  44029. }
  44030. };
  44031. ArcRotateCamera.prototype._checkInputs = function () {
  44032. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44033. if (this._collisionTriggered) {
  44034. return;
  44035. }
  44036. this.inputs.checkInputs();
  44037. // Inertia
  44038. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44039. if (this.getScene().useRightHandedSystem) {
  44040. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44041. }
  44042. else {
  44043. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44044. }
  44045. this.beta += this.inertialBetaOffset;
  44046. this.radius -= this.inertialRadiusOffset;
  44047. this.inertialAlphaOffset *= this.inertia;
  44048. this.inertialBetaOffset *= this.inertia;
  44049. this.inertialRadiusOffset *= this.inertia;
  44050. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44051. this.inertialAlphaOffset = 0;
  44052. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44053. this.inertialBetaOffset = 0;
  44054. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44055. this.inertialRadiusOffset = 0;
  44056. }
  44057. // Panning inertia
  44058. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44059. if (!this._localDirection) {
  44060. this._localDirection = BABYLON.Vector3.Zero();
  44061. this._transformedDirection = BABYLON.Vector3.Zero();
  44062. }
  44063. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44064. this._localDirection.multiplyInPlace(this.panningAxis);
  44065. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44066. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44067. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44068. if (!this.panningAxis.y) {
  44069. this._transformedDirection.y = 0;
  44070. }
  44071. if (!this._targetHost) {
  44072. if (this.panningDistanceLimit) {
  44073. this._transformedDirection.addInPlace(this._target);
  44074. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44075. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44076. this._target.copyFrom(this._transformedDirection);
  44077. }
  44078. }
  44079. else {
  44080. this._target.addInPlace(this._transformedDirection);
  44081. }
  44082. }
  44083. this.inertialPanningX *= this.panningInertia;
  44084. this.inertialPanningY *= this.panningInertia;
  44085. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44086. this.inertialPanningX = 0;
  44087. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44088. this.inertialPanningY = 0;
  44089. }
  44090. // Limits
  44091. this._checkLimits();
  44092. _super.prototype._checkInputs.call(this);
  44093. };
  44094. ArcRotateCamera.prototype._checkLimits = function () {
  44095. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44096. if (this.allowUpsideDown && this.beta > Math.PI) {
  44097. this.beta = this.beta - (2 * Math.PI);
  44098. }
  44099. }
  44100. else {
  44101. if (this.beta < this.lowerBetaLimit) {
  44102. this.beta = this.lowerBetaLimit;
  44103. }
  44104. }
  44105. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44106. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44107. this.beta = this.beta + (2 * Math.PI);
  44108. }
  44109. }
  44110. else {
  44111. if (this.beta > this.upperBetaLimit) {
  44112. this.beta = this.upperBetaLimit;
  44113. }
  44114. }
  44115. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44116. this.alpha = this.lowerAlphaLimit;
  44117. }
  44118. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44119. this.alpha = this.upperAlphaLimit;
  44120. }
  44121. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44122. this.radius = this.lowerRadiusLimit;
  44123. }
  44124. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44125. this.radius = this.upperRadiusLimit;
  44126. }
  44127. };
  44128. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44129. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44130. this.radius = radiusv3.length();
  44131. if (this.radius === 0) {
  44132. this.radius = 0.0001; // Just to avoid division by zero
  44133. }
  44134. // Alpha
  44135. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44136. if (radiusv3.z < 0) {
  44137. this.alpha = 2 * Math.PI - this.alpha;
  44138. }
  44139. // Beta
  44140. this.beta = Math.acos(radiusv3.y / this.radius);
  44141. this._checkLimits();
  44142. };
  44143. ArcRotateCamera.prototype.setPosition = function (position) {
  44144. if (this.position.equals(position)) {
  44145. return;
  44146. }
  44147. this.position.copyFrom(position);
  44148. this.rebuildAnglesAndRadius();
  44149. };
  44150. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44151. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44152. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44153. if (target.getBoundingInfo) {
  44154. if (toBoundingCenter) {
  44155. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44156. }
  44157. else {
  44158. this._targetBoundingCenter = null;
  44159. }
  44160. this._targetHost = target;
  44161. this._target = this._getTargetPosition();
  44162. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44163. }
  44164. else {
  44165. var newTarget = target;
  44166. var currentTarget = this._getTargetPosition();
  44167. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44168. return;
  44169. }
  44170. this._targetHost = null;
  44171. this._target = newTarget;
  44172. this._targetBoundingCenter = null;
  44173. this.onMeshTargetChangedObservable.notifyObservers(null);
  44174. }
  44175. this.rebuildAnglesAndRadius();
  44176. };
  44177. ArcRotateCamera.prototype._getViewMatrix = function () {
  44178. // Compute
  44179. var cosa = Math.cos(this.alpha);
  44180. var sina = Math.sin(this.alpha);
  44181. var cosb = Math.cos(this.beta);
  44182. var sinb = Math.sin(this.beta);
  44183. if (sinb === 0) {
  44184. sinb = 0.0001;
  44185. }
  44186. var target = this._getTargetPosition();
  44187. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44188. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44189. if (!this._collider) {
  44190. this._collider = new BABYLON.Collider();
  44191. }
  44192. this._collider._radius = this.collisionRadius;
  44193. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44194. this._collisionTriggered = true;
  44195. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44196. }
  44197. else {
  44198. this.position.copyFrom(this._newPosition);
  44199. var up = this.upVector;
  44200. if (this.allowUpsideDown && sinb < 0) {
  44201. up = up.clone();
  44202. up = up.negate();
  44203. }
  44204. if (this.getScene().useRightHandedSystem) {
  44205. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44206. }
  44207. else {
  44208. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44209. }
  44210. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44211. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44212. }
  44213. this._currentTarget = target;
  44214. return this._viewMatrix;
  44215. };
  44216. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44217. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44218. meshes = meshes || this.getScene().meshes;
  44219. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44220. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44221. this.radius = distance * this.zoomOnFactor;
  44222. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44223. };
  44224. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44225. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44226. var meshesOrMinMaxVector;
  44227. var distance;
  44228. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44229. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44230. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44231. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44232. }
  44233. else {
  44234. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44235. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44236. distance = minMaxVectorAndDistance.distance;
  44237. }
  44238. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44239. if (!doNotUpdateMaxZ) {
  44240. this.maxZ = distance * 2;
  44241. }
  44242. };
  44243. /**
  44244. * @override
  44245. * Override Camera.createRigCamera
  44246. */
  44247. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44248. var alphaShift = 0;
  44249. switch (this.cameraRigMode) {
  44250. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44251. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44252. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44253. case BABYLON.Camera.RIG_MODE_VR:
  44254. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44255. break;
  44256. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44257. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44258. break;
  44259. }
  44260. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44261. rigCam._cameraRigParams = {};
  44262. return rigCam;
  44263. };
  44264. /**
  44265. * @override
  44266. * Override Camera._updateRigCameras
  44267. */
  44268. ArcRotateCamera.prototype._updateRigCameras = function () {
  44269. var camLeft = this._rigCameras[0];
  44270. var camRight = this._rigCameras[1];
  44271. camLeft.beta = camRight.beta = this.beta;
  44272. camLeft.radius = camRight.radius = this.radius;
  44273. switch (this.cameraRigMode) {
  44274. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44275. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44276. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44277. case BABYLON.Camera.RIG_MODE_VR:
  44278. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44279. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44280. break;
  44281. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44282. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44283. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44284. break;
  44285. }
  44286. _super.prototype._updateRigCameras.call(this);
  44287. };
  44288. ArcRotateCamera.prototype.dispose = function () {
  44289. this.inputs.clear();
  44290. _super.prototype.dispose.call(this);
  44291. };
  44292. ArcRotateCamera.prototype.getClassName = function () {
  44293. return "ArcRotateCamera";
  44294. };
  44295. __decorate([
  44296. BABYLON.serialize()
  44297. ], ArcRotateCamera.prototype, "alpha", void 0);
  44298. __decorate([
  44299. BABYLON.serialize()
  44300. ], ArcRotateCamera.prototype, "beta", void 0);
  44301. __decorate([
  44302. BABYLON.serialize()
  44303. ], ArcRotateCamera.prototype, "radius", void 0);
  44304. __decorate([
  44305. BABYLON.serializeAsVector3("target")
  44306. ], ArcRotateCamera.prototype, "_target", void 0);
  44307. __decorate([
  44308. BABYLON.serialize()
  44309. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44310. __decorate([
  44311. BABYLON.serialize()
  44312. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44313. __decorate([
  44314. BABYLON.serialize()
  44315. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44316. __decorate([
  44317. BABYLON.serialize()
  44318. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44319. __decorate([
  44320. BABYLON.serialize()
  44321. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44322. __decorate([
  44323. BABYLON.serialize()
  44324. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44325. __decorate([
  44326. BABYLON.serialize()
  44327. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44328. __decorate([
  44329. BABYLON.serialize()
  44330. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44331. __decorate([
  44332. BABYLON.serialize()
  44333. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44334. __decorate([
  44335. BABYLON.serialize()
  44336. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44337. __decorate([
  44338. BABYLON.serialize()
  44339. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44340. __decorate([
  44341. BABYLON.serialize()
  44342. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44343. __decorate([
  44344. BABYLON.serialize()
  44345. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44346. __decorate([
  44347. BABYLON.serializeAsVector3()
  44348. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44349. __decorate([
  44350. BABYLON.serialize()
  44351. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44352. __decorate([
  44353. BABYLON.serialize()
  44354. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44355. __decorate([
  44356. BABYLON.serialize()
  44357. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44358. return ArcRotateCamera;
  44359. }(BABYLON.TargetCamera));
  44360. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44361. })(BABYLON || (BABYLON = {}));
  44362. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44363. var BABYLON;
  44364. (function (BABYLON) {
  44365. /**
  44366. * The HemisphericLight simulates the ambient environment light,
  44367. * so the passed direction is the light reflection direction, not the incoming direction.
  44368. */
  44369. var HemisphericLight = /** @class */ (function (_super) {
  44370. __extends(HemisphericLight, _super);
  44371. /**
  44372. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44373. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44374. * The HemisphericLight can't cast shadows.
  44375. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44376. * @param name The friendly name of the light
  44377. * @param direction The direction of the light reflection
  44378. * @param scene The scene the light belongs to
  44379. */
  44380. function HemisphericLight(name, direction, scene) {
  44381. var _this = _super.call(this, name, scene) || this;
  44382. /**
  44383. * The groundColor is the light in the opposite direction to the one specified during creation.
  44384. * 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.
  44385. */
  44386. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44387. _this.direction = direction || BABYLON.Vector3.Up();
  44388. return _this;
  44389. }
  44390. HemisphericLight.prototype._buildUniformLayout = function () {
  44391. this._uniformBuffer.addUniform("vLightData", 4);
  44392. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44393. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44394. this._uniformBuffer.addUniform("vLightGround", 3);
  44395. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44396. this._uniformBuffer.addUniform("depthValues", 2);
  44397. this._uniformBuffer.create();
  44398. };
  44399. /**
  44400. * Returns the string "HemisphericLight".
  44401. * @return The class name
  44402. */
  44403. HemisphericLight.prototype.getClassName = function () {
  44404. return "HemisphericLight";
  44405. };
  44406. /**
  44407. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44408. * Returns the updated direction.
  44409. * @param target The target the direction should point to
  44410. * @return The computed direction
  44411. */
  44412. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44413. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44414. return this.direction;
  44415. };
  44416. /**
  44417. * Returns the shadow generator associated to the light.
  44418. * @returns Always null for hemispheric lights because it does not support shadows.
  44419. */
  44420. HemisphericLight.prototype.getShadowGenerator = function () {
  44421. return null;
  44422. };
  44423. /**
  44424. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44425. * @param effect The effect to update
  44426. * @param lightIndex The index of the light in the effect to update
  44427. * @returns The hemispheric light
  44428. */
  44429. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44430. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44431. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44432. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44433. return this;
  44434. };
  44435. /**
  44436. * @ignore internal use only.
  44437. */
  44438. HemisphericLight.prototype._getWorldMatrix = function () {
  44439. if (!this._worldMatrix) {
  44440. this._worldMatrix = BABYLON.Matrix.Identity();
  44441. }
  44442. return this._worldMatrix;
  44443. };
  44444. /**
  44445. * Returns the integer 3.
  44446. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44447. */
  44448. HemisphericLight.prototype.getTypeID = function () {
  44449. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44450. };
  44451. __decorate([
  44452. BABYLON.serializeAsColor3()
  44453. ], HemisphericLight.prototype, "groundColor", void 0);
  44454. __decorate([
  44455. BABYLON.serializeAsVector3()
  44456. ], HemisphericLight.prototype, "direction", void 0);
  44457. return HemisphericLight;
  44458. }(BABYLON.Light));
  44459. BABYLON.HemisphericLight = HemisphericLight;
  44460. })(BABYLON || (BABYLON = {}));
  44461. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44462. var BABYLON;
  44463. (function (BABYLON) {
  44464. /**
  44465. * Base implementation of @see IShadowLight
  44466. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44467. */
  44468. var ShadowLight = /** @class */ (function (_super) {
  44469. __extends(ShadowLight, _super);
  44470. function ShadowLight() {
  44471. var _this = _super !== null && _super.apply(this, arguments) || this;
  44472. _this._needProjectionMatrixCompute = true;
  44473. return _this;
  44474. }
  44475. ShadowLight.prototype._setPosition = function (value) {
  44476. this._position = value;
  44477. };
  44478. Object.defineProperty(ShadowLight.prototype, "position", {
  44479. /**
  44480. * Sets the position the shadow will be casted from. Also use as the light position for both
  44481. * point and spot lights.
  44482. */
  44483. get: function () {
  44484. return this._position;
  44485. },
  44486. /**
  44487. * Sets the position the shadow will be casted from. Also use as the light position for both
  44488. * point and spot lights.
  44489. */
  44490. set: function (value) {
  44491. this._setPosition(value);
  44492. },
  44493. enumerable: true,
  44494. configurable: true
  44495. });
  44496. ShadowLight.prototype._setDirection = function (value) {
  44497. this._direction = value;
  44498. };
  44499. Object.defineProperty(ShadowLight.prototype, "direction", {
  44500. /**
  44501. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44502. * Also use as the light direction on spot and directional lights.
  44503. */
  44504. get: function () {
  44505. return this._direction;
  44506. },
  44507. /**
  44508. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44509. * Also use as the light direction on spot and directional lights.
  44510. */
  44511. set: function (value) {
  44512. this._setDirection(value);
  44513. },
  44514. enumerable: true,
  44515. configurable: true
  44516. });
  44517. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44518. /**
  44519. * Gets the shadow projection clipping minimum z value.
  44520. */
  44521. get: function () {
  44522. return this._shadowMinZ;
  44523. },
  44524. /**
  44525. * Sets the shadow projection clipping minimum z value.
  44526. */
  44527. set: function (value) {
  44528. this._shadowMinZ = value;
  44529. this.forceProjectionMatrixCompute();
  44530. },
  44531. enumerable: true,
  44532. configurable: true
  44533. });
  44534. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44535. /**
  44536. * Sets the shadow projection clipping maximum z value.
  44537. */
  44538. get: function () {
  44539. return this._shadowMaxZ;
  44540. },
  44541. /**
  44542. * Gets the shadow projection clipping maximum z value.
  44543. */
  44544. set: function (value) {
  44545. this._shadowMaxZ = value;
  44546. this.forceProjectionMatrixCompute();
  44547. },
  44548. enumerable: true,
  44549. configurable: true
  44550. });
  44551. /**
  44552. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44553. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44554. */
  44555. ShadowLight.prototype.computeTransformedInformation = function () {
  44556. if (this.parent && this.parent.getWorldMatrix) {
  44557. if (!this.transformedPosition) {
  44558. this.transformedPosition = BABYLON.Vector3.Zero();
  44559. }
  44560. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44561. // In case the direction is present.
  44562. if (this.direction) {
  44563. if (!this.transformedDirection) {
  44564. this.transformedDirection = BABYLON.Vector3.Zero();
  44565. }
  44566. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44567. }
  44568. return true;
  44569. }
  44570. return false;
  44571. };
  44572. /**
  44573. * Return the depth scale used for the shadow map.
  44574. * @returns the depth scale.
  44575. */
  44576. ShadowLight.prototype.getDepthScale = function () {
  44577. return 50.0;
  44578. };
  44579. /**
  44580. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44581. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44582. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44583. */
  44584. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44585. return this.transformedDirection ? this.transformedDirection : this.direction;
  44586. };
  44587. /**
  44588. * Returns the ShadowLight absolute position in the World.
  44589. * @returns the position vector in world space
  44590. */
  44591. ShadowLight.prototype.getAbsolutePosition = function () {
  44592. return this.transformedPosition ? this.transformedPosition : this.position;
  44593. };
  44594. /**
  44595. * Sets the ShadowLight direction toward the passed target.
  44596. * @param target The point tot target in local space
  44597. * @returns the updated ShadowLight direction
  44598. */
  44599. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44600. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44601. return this.direction;
  44602. };
  44603. /**
  44604. * Returns the light rotation in euler definition.
  44605. * @returns the x y z rotation in local space.
  44606. */
  44607. ShadowLight.prototype.getRotation = function () {
  44608. this.direction.normalize();
  44609. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44610. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44611. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44612. };
  44613. /**
  44614. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  44615. * @returns true if a cube texture needs to be use
  44616. */
  44617. ShadowLight.prototype.needCube = function () {
  44618. return false;
  44619. };
  44620. /**
  44621. * Detects if the projection matrix requires to be recomputed this frame.
  44622. * @returns true if it requires to be recomputed otherwise, false.
  44623. */
  44624. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  44625. return this._needProjectionMatrixCompute;
  44626. };
  44627. /**
  44628. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  44629. */
  44630. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  44631. this._needProjectionMatrixCompute = true;
  44632. };
  44633. /**
  44634. * Get the world matrix of the sahdow lights.
  44635. * @ignore Internal Use Only
  44636. */
  44637. ShadowLight.prototype._getWorldMatrix = function () {
  44638. if (!this._worldMatrix) {
  44639. this._worldMatrix = BABYLON.Matrix.Identity();
  44640. }
  44641. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  44642. return this._worldMatrix;
  44643. };
  44644. /**
  44645. * Gets the minZ used for shadow according to both the scene and the light.
  44646. * @param activeCamera The camera we are returning the min for
  44647. * @returns the depth min z
  44648. */
  44649. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  44650. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  44651. };
  44652. /**
  44653. * Gets the maxZ used for shadow according to both the scene and the light.
  44654. * @param activeCamera The camera we are returning the max for
  44655. * @returns the depth max z
  44656. */
  44657. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  44658. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  44659. };
  44660. /**
  44661. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  44662. * @param matrix The materix to updated with the projection information
  44663. * @param viewMatrix The transform matrix of the light
  44664. * @param renderList The list of mesh to render in the map
  44665. * @returns The current light
  44666. */
  44667. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44668. if (this.customProjectionMatrixBuilder) {
  44669. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  44670. }
  44671. else {
  44672. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44673. }
  44674. return this;
  44675. };
  44676. __decorate([
  44677. BABYLON.serializeAsVector3()
  44678. ], ShadowLight.prototype, "position", null);
  44679. __decorate([
  44680. BABYLON.serializeAsVector3()
  44681. ], ShadowLight.prototype, "direction", null);
  44682. __decorate([
  44683. BABYLON.serialize()
  44684. ], ShadowLight.prototype, "shadowMinZ", null);
  44685. __decorate([
  44686. BABYLON.serialize()
  44687. ], ShadowLight.prototype, "shadowMaxZ", null);
  44688. return ShadowLight;
  44689. }(BABYLON.Light));
  44690. BABYLON.ShadowLight = ShadowLight;
  44691. })(BABYLON || (BABYLON = {}));
  44692. //# sourceMappingURL=babylon.shadowLight.js.map
  44693. var BABYLON;
  44694. (function (BABYLON) {
  44695. /**
  44696. * A point light is a light defined by an unique point in world space.
  44697. * The light is emitted in every direction from this point.
  44698. * A good example of a point light is a standard light bulb.
  44699. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44700. */
  44701. var PointLight = /** @class */ (function (_super) {
  44702. __extends(PointLight, _super);
  44703. /**
  44704. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  44705. * A PointLight emits the light in every direction.
  44706. * It can cast shadows.
  44707. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  44708. * ```javascript
  44709. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  44710. * ```
  44711. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44712. * @param name The light friendly name
  44713. * @param position The position of the point light in the scene
  44714. * @param scene The scene the lights belongs to
  44715. */
  44716. function PointLight(name, position, scene) {
  44717. var _this = _super.call(this, name, scene) || this;
  44718. _this._shadowAngle = Math.PI / 2;
  44719. _this.position = position;
  44720. return _this;
  44721. }
  44722. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  44723. /**
  44724. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44725. * This specifies what angle the shadow will use to be created.
  44726. *
  44727. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44728. */
  44729. get: function () {
  44730. return this._shadowAngle;
  44731. },
  44732. /**
  44733. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44734. * This specifies what angle the shadow will use to be created.
  44735. *
  44736. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44737. */
  44738. set: function (value) {
  44739. this._shadowAngle = value;
  44740. this.forceProjectionMatrixCompute();
  44741. },
  44742. enumerable: true,
  44743. configurable: true
  44744. });
  44745. Object.defineProperty(PointLight.prototype, "direction", {
  44746. /**
  44747. * Gets the direction if it has been set.
  44748. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44749. */
  44750. get: function () {
  44751. return this._direction;
  44752. },
  44753. /**
  44754. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44755. */
  44756. set: function (value) {
  44757. var previousNeedCube = this.needCube();
  44758. this._direction = value;
  44759. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  44760. this._shadowGenerator.recreateShadowMap();
  44761. }
  44762. },
  44763. enumerable: true,
  44764. configurable: true
  44765. });
  44766. /**
  44767. * Returns the string "PointLight"
  44768. * @returns the class name
  44769. */
  44770. PointLight.prototype.getClassName = function () {
  44771. return "PointLight";
  44772. };
  44773. /**
  44774. * Returns the integer 0.
  44775. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44776. */
  44777. PointLight.prototype.getTypeID = function () {
  44778. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  44779. };
  44780. /**
  44781. * Specifies wether or not the shadowmap should be a cube texture.
  44782. * @returns true if the shadowmap needs to be a cube texture.
  44783. */
  44784. PointLight.prototype.needCube = function () {
  44785. return !this.direction;
  44786. };
  44787. /**
  44788. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  44789. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44790. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44791. */
  44792. PointLight.prototype.getShadowDirection = function (faceIndex) {
  44793. if (this.direction) {
  44794. return _super.prototype.getShadowDirection.call(this, faceIndex);
  44795. }
  44796. else {
  44797. switch (faceIndex) {
  44798. case 0:
  44799. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  44800. case 1:
  44801. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  44802. case 2:
  44803. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  44804. case 3:
  44805. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  44806. case 4:
  44807. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  44808. case 5:
  44809. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  44810. }
  44811. }
  44812. return BABYLON.Vector3.Zero();
  44813. };
  44814. /**
  44815. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  44816. * - fov = PI / 2
  44817. * - aspect ratio : 1.0
  44818. * - z-near and far equal to the active camera minZ and maxZ.
  44819. * Returns the PointLight.
  44820. */
  44821. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44822. var activeCamera = this.getScene().activeCamera;
  44823. if (!activeCamera) {
  44824. return;
  44825. }
  44826. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  44827. };
  44828. PointLight.prototype._buildUniformLayout = function () {
  44829. this._uniformBuffer.addUniform("vLightData", 4);
  44830. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44831. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44832. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44833. this._uniformBuffer.addUniform("depthValues", 2);
  44834. this._uniformBuffer.create();
  44835. };
  44836. /**
  44837. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  44838. * @param effect The effect to update
  44839. * @param lightIndex The index of the light in the effect to update
  44840. * @returns The point light
  44841. */
  44842. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  44843. if (this.computeTransformedInformation()) {
  44844. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  44845. return this;
  44846. }
  44847. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  44848. return this;
  44849. };
  44850. __decorate([
  44851. BABYLON.serialize()
  44852. ], PointLight.prototype, "shadowAngle", null);
  44853. return PointLight;
  44854. }(BABYLON.ShadowLight));
  44855. BABYLON.PointLight = PointLight;
  44856. })(BABYLON || (BABYLON = {}));
  44857. //# sourceMappingURL=babylon.pointLight.js.map
  44858. var BABYLON;
  44859. (function (BABYLON) {
  44860. /**
  44861. * A directional light is defined by a direction (what a surprise!).
  44862. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  44863. * 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.
  44864. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44865. */
  44866. var DirectionalLight = /** @class */ (function (_super) {
  44867. __extends(DirectionalLight, _super);
  44868. /**
  44869. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  44870. * The directional light is emitted from everywhere in the given direction.
  44871. * It can cast shawdows.
  44872. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44873. * @param name The friendly name of the light
  44874. * @param direction The direction of the light
  44875. * @param scene The scene the light belongs to
  44876. */
  44877. function DirectionalLight(name, direction, scene) {
  44878. var _this = _super.call(this, name, scene) || this;
  44879. _this._shadowFrustumSize = 0;
  44880. _this._shadowOrthoScale = 0.5;
  44881. /**
  44882. * Automatically compute the projection matrix to best fit (including all the casters)
  44883. * on each frame.
  44884. */
  44885. _this.autoUpdateExtends = true;
  44886. // Cache
  44887. _this._orthoLeft = Number.MAX_VALUE;
  44888. _this._orthoRight = Number.MIN_VALUE;
  44889. _this._orthoTop = Number.MIN_VALUE;
  44890. _this._orthoBottom = Number.MAX_VALUE;
  44891. _this.position = direction.scale(-1.0);
  44892. _this.direction = direction;
  44893. return _this;
  44894. }
  44895. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  44896. /**
  44897. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  44898. */
  44899. get: function () {
  44900. return this._shadowFrustumSize;
  44901. },
  44902. /**
  44903. * Specifies a fix frustum size for the shadow generation.
  44904. */
  44905. set: function (value) {
  44906. this._shadowFrustumSize = value;
  44907. this.forceProjectionMatrixCompute();
  44908. },
  44909. enumerable: true,
  44910. configurable: true
  44911. });
  44912. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  44913. /**
  44914. * Gets the shadow projection scale against the optimal computed one.
  44915. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  44916. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  44917. */
  44918. get: function () {
  44919. return this._shadowOrthoScale;
  44920. },
  44921. /**
  44922. * Sets the shadow projection scale against the optimal computed one.
  44923. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  44924. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  44925. */
  44926. set: function (value) {
  44927. this._shadowOrthoScale = value;
  44928. this.forceProjectionMatrixCompute();
  44929. },
  44930. enumerable: true,
  44931. configurable: true
  44932. });
  44933. /**
  44934. * Returns the string "DirectionalLight".
  44935. * @return The class name
  44936. */
  44937. DirectionalLight.prototype.getClassName = function () {
  44938. return "DirectionalLight";
  44939. };
  44940. /**
  44941. * Returns the integer 1.
  44942. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44943. */
  44944. DirectionalLight.prototype.getTypeID = function () {
  44945. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  44946. };
  44947. /**
  44948. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  44949. * Returns the DirectionalLight Shadow projection matrix.
  44950. */
  44951. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44952. if (this.shadowFrustumSize > 0) {
  44953. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  44954. }
  44955. else {
  44956. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44957. }
  44958. };
  44959. /**
  44960. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  44961. * Returns the DirectionalLight Shadow projection matrix.
  44962. */
  44963. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  44964. var activeCamera = this.getScene().activeCamera;
  44965. if (!activeCamera) {
  44966. return;
  44967. }
  44968. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  44969. };
  44970. /**
  44971. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  44972. * Returns the DirectionalLight Shadow projection matrix.
  44973. */
  44974. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44975. var activeCamera = this.getScene().activeCamera;
  44976. if (!activeCamera) {
  44977. return;
  44978. }
  44979. // Check extends
  44980. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  44981. var tempVector3 = BABYLON.Vector3.Zero();
  44982. this._orthoLeft = Number.MAX_VALUE;
  44983. this._orthoRight = Number.MIN_VALUE;
  44984. this._orthoTop = Number.MIN_VALUE;
  44985. this._orthoBottom = Number.MAX_VALUE;
  44986. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  44987. var mesh = renderList[meshIndex];
  44988. if (!mesh) {
  44989. continue;
  44990. }
  44991. var boundingInfo = mesh.getBoundingInfo();
  44992. var boundingBox = boundingInfo.boundingBox;
  44993. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  44994. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  44995. if (tempVector3.x < this._orthoLeft)
  44996. this._orthoLeft = tempVector3.x;
  44997. if (tempVector3.y < this._orthoBottom)
  44998. this._orthoBottom = tempVector3.y;
  44999. if (tempVector3.x > this._orthoRight)
  45000. this._orthoRight = tempVector3.x;
  45001. if (tempVector3.y > this._orthoTop)
  45002. this._orthoTop = tempVector3.y;
  45003. }
  45004. }
  45005. }
  45006. var xOffset = this._orthoRight - this._orthoLeft;
  45007. var yOffset = this._orthoTop - this._orthoBottom;
  45008. 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);
  45009. };
  45010. DirectionalLight.prototype._buildUniformLayout = function () {
  45011. this._uniformBuffer.addUniform("vLightData", 4);
  45012. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45013. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45014. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45015. this._uniformBuffer.addUniform("depthValues", 2);
  45016. this._uniformBuffer.create();
  45017. };
  45018. /**
  45019. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45020. * @param effect The effect to update
  45021. * @param lightIndex The index of the light in the effect to update
  45022. * @returns The directional light
  45023. */
  45024. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45025. if (this.computeTransformedInformation()) {
  45026. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45027. return this;
  45028. }
  45029. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45030. return this;
  45031. };
  45032. /**
  45033. * Gets the minZ used for shadow according to both the scene and the light.
  45034. *
  45035. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45036. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45037. * @param activeCamera The camera we are returning the min for
  45038. * @returns the depth min z
  45039. */
  45040. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45041. return 1;
  45042. };
  45043. /**
  45044. * Gets the maxZ used for shadow according to both the scene and the light.
  45045. *
  45046. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45047. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45048. * @param activeCamera The camera we are returning the max for
  45049. * @returns the depth max z
  45050. */
  45051. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45052. return 1;
  45053. };
  45054. __decorate([
  45055. BABYLON.serialize()
  45056. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45057. __decorate([
  45058. BABYLON.serialize()
  45059. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45060. __decorate([
  45061. BABYLON.serialize()
  45062. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45063. return DirectionalLight;
  45064. }(BABYLON.ShadowLight));
  45065. BABYLON.DirectionalLight = DirectionalLight;
  45066. })(BABYLON || (BABYLON = {}));
  45067. //# sourceMappingURL=babylon.directionalLight.js.map
  45068. var BABYLON;
  45069. (function (BABYLON) {
  45070. /**
  45071. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45072. * These values define a cone of light starting from the position, emitting toward the direction.
  45073. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45074. * and the exponent defines the speed of the decay of the light with distance (reach).
  45075. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45076. */
  45077. var SpotLight = /** @class */ (function (_super) {
  45078. __extends(SpotLight, _super);
  45079. /**
  45080. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45081. * It can cast shadows.
  45082. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45083. * @param name The light friendly name
  45084. * @param position The position of the spot light in the scene
  45085. * @param direction The direction of the light in the scene
  45086. * @param angle The cone angle of the light in Radians
  45087. * @param exponent The light decay speed with the distance from the emission spot
  45088. * @param scene The scene the lights belongs to
  45089. */
  45090. function SpotLight(name, position, direction, angle, exponent, scene) {
  45091. var _this = _super.call(this, name, scene) || this;
  45092. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45093. _this._projectionTextureLightNear = 1e-6;
  45094. _this._projectionTextureLightFar = 1000.0;
  45095. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45096. _this._projectionTextureViewLightDirty = true;
  45097. _this._projectionTextureProjectionLightDirty = true;
  45098. _this._projectionTextureDirty = true;
  45099. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45100. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45101. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45102. _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);
  45103. _this.position = position;
  45104. _this.direction = direction;
  45105. _this.angle = angle;
  45106. _this.exponent = exponent;
  45107. return _this;
  45108. }
  45109. Object.defineProperty(SpotLight.prototype, "angle", {
  45110. /**
  45111. * Gets the cone angle of the spot light in Radians.
  45112. */
  45113. get: function () {
  45114. return this._angle;
  45115. },
  45116. /**
  45117. * Sets the cone angle of the spot light in Radians.
  45118. */
  45119. set: function (value) {
  45120. this._angle = value;
  45121. this._projectionTextureProjectionLightDirty = true;
  45122. this.forceProjectionMatrixCompute();
  45123. },
  45124. enumerable: true,
  45125. configurable: true
  45126. });
  45127. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45128. /**
  45129. * Allows scaling the angle of the light for shadow generation only.
  45130. */
  45131. get: function () {
  45132. return this._shadowAngleScale;
  45133. },
  45134. /**
  45135. * Allows scaling the angle of the light for shadow generation only.
  45136. */
  45137. set: function (value) {
  45138. this._shadowAngleScale = value;
  45139. this.forceProjectionMatrixCompute();
  45140. },
  45141. enumerable: true,
  45142. configurable: true
  45143. });
  45144. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45145. /**
  45146. * Allows reading the projecton texture
  45147. */
  45148. get: function () {
  45149. return this._projectionTextureMatrix;
  45150. },
  45151. enumerable: true,
  45152. configurable: true
  45153. });
  45154. ;
  45155. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45156. /**
  45157. * Gets the near clip of the Spotlight for texture projection.
  45158. */
  45159. get: function () {
  45160. return this._projectionTextureLightNear;
  45161. },
  45162. /**
  45163. * Sets the near clip of the Spotlight for texture projection.
  45164. */
  45165. set: function (value) {
  45166. this._projectionTextureLightNear = value;
  45167. this._projectionTextureProjectionLightDirty = true;
  45168. },
  45169. enumerable: true,
  45170. configurable: true
  45171. });
  45172. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45173. /**
  45174. * Gets the far clip of the Spotlight for texture projection.
  45175. */
  45176. get: function () {
  45177. return this._projectionTextureLightFar;
  45178. },
  45179. /**
  45180. * Sets the far clip of the Spotlight for texture projection.
  45181. */
  45182. set: function (value) {
  45183. this._projectionTextureLightFar = value;
  45184. this._projectionTextureProjectionLightDirty = true;
  45185. },
  45186. enumerable: true,
  45187. configurable: true
  45188. });
  45189. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45190. /**
  45191. * Gets the Up vector of the Spotlight for texture projection.
  45192. */
  45193. get: function () {
  45194. return this._projectionTextureUpDirection;
  45195. },
  45196. /**
  45197. * Sets the Up vector of the Spotlight for texture projection.
  45198. */
  45199. set: function (value) {
  45200. this._projectionTextureUpDirection = value;
  45201. this._projectionTextureProjectionLightDirty = true;
  45202. },
  45203. enumerable: true,
  45204. configurable: true
  45205. });
  45206. ;
  45207. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45208. /**
  45209. * Gets the projection texture of the light.
  45210. */
  45211. get: function () {
  45212. return this._projectionTexture;
  45213. },
  45214. /**
  45215. * Sets the projection texture of the light.
  45216. */
  45217. set: function (value) {
  45218. this._projectionTexture = value;
  45219. this._projectionTextureDirty = true;
  45220. },
  45221. enumerable: true,
  45222. configurable: true
  45223. });
  45224. /**
  45225. * Returns the string "SpotLight".
  45226. * @returns the class name
  45227. */
  45228. SpotLight.prototype.getClassName = function () {
  45229. return "SpotLight";
  45230. };
  45231. /**
  45232. * Returns the integer 2.
  45233. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45234. */
  45235. SpotLight.prototype.getTypeID = function () {
  45236. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45237. };
  45238. /**
  45239. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45240. */
  45241. SpotLight.prototype._setDirection = function (value) {
  45242. _super.prototype._setDirection.call(this, value);
  45243. this._projectionTextureViewLightDirty = true;
  45244. };
  45245. /**
  45246. * Overrides the position setter to recompute the projection texture view light Matrix.
  45247. */
  45248. SpotLight.prototype._setPosition = function (value) {
  45249. _super.prototype._setPosition.call(this, value);
  45250. this._projectionTextureViewLightDirty = true;
  45251. };
  45252. /**
  45253. * 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.
  45254. * Returns the SpotLight.
  45255. */
  45256. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45257. var activeCamera = this.getScene().activeCamera;
  45258. if (!activeCamera) {
  45259. return;
  45260. }
  45261. this._shadowAngleScale = this._shadowAngleScale || 1;
  45262. var angle = this._shadowAngleScale * this._angle;
  45263. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45264. };
  45265. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45266. this._projectionTextureViewLightDirty = false;
  45267. this._projectionTextureDirty = true;
  45268. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45269. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45270. };
  45271. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45272. this._projectionTextureProjectionLightDirty = false;
  45273. this._projectionTextureDirty = true;
  45274. var light_far = this.projectionTextureLightFar;
  45275. var light_near = this.projectionTextureLightNear;
  45276. var P = light_far / (light_far - light_near);
  45277. var Q = -P * light_near;
  45278. var S = 1.0 / Math.tan(this._angle / 2.0);
  45279. var A = 1.0;
  45280. 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);
  45281. };
  45282. /**
  45283. * Main function for light texture projection matrix computing.
  45284. */
  45285. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45286. this._projectionTextureDirty = false;
  45287. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45288. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45289. };
  45290. SpotLight.prototype._buildUniformLayout = function () {
  45291. this._uniformBuffer.addUniform("vLightData", 4);
  45292. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45293. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45294. this._uniformBuffer.addUniform("vLightDirection", 3);
  45295. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45296. this._uniformBuffer.addUniform("depthValues", 2);
  45297. this._uniformBuffer.create();
  45298. };
  45299. /**
  45300. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45301. * @param effect The effect to update
  45302. * @param lightIndex The index of the light in the effect to update
  45303. * @returns The spot light
  45304. */
  45305. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45306. var normalizeDirection;
  45307. if (this.computeTransformedInformation()) {
  45308. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45309. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45310. }
  45311. else {
  45312. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45313. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45314. }
  45315. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45316. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45317. if (this._projectionTextureViewLightDirty) {
  45318. this._computeProjectionTextureViewLightMatrix();
  45319. }
  45320. if (this._projectionTextureProjectionLightDirty) {
  45321. this._computeProjectionTextureProjectionLightMatrix();
  45322. }
  45323. if (this._projectionTextureDirty) {
  45324. this._computeProjectionTextureMatrix();
  45325. }
  45326. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45327. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45328. }
  45329. return this;
  45330. };
  45331. /**
  45332. * Disposes the light and the associated resources.
  45333. */
  45334. SpotLight.prototype.dispose = function () {
  45335. _super.prototype.dispose.call(this);
  45336. if (this._projectionTexture) {
  45337. this._projectionTexture.dispose();
  45338. }
  45339. };
  45340. __decorate([
  45341. BABYLON.serialize()
  45342. ], SpotLight.prototype, "angle", null);
  45343. __decorate([
  45344. BABYLON.serialize()
  45345. ], SpotLight.prototype, "shadowAngleScale", null);
  45346. __decorate([
  45347. BABYLON.serialize()
  45348. ], SpotLight.prototype, "exponent", void 0);
  45349. __decorate([
  45350. BABYLON.serialize()
  45351. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45352. __decorate([
  45353. BABYLON.serialize()
  45354. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45355. __decorate([
  45356. BABYLON.serialize()
  45357. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45358. __decorate([
  45359. BABYLON.serializeAsTexture("projectedLightTexture")
  45360. ], SpotLight.prototype, "_projectionTexture", void 0);
  45361. return SpotLight;
  45362. }(BABYLON.ShadowLight));
  45363. BABYLON.SpotLight = SpotLight;
  45364. })(BABYLON || (BABYLON = {}));
  45365. //# sourceMappingURL=babylon.spotLight.js.map
  45366. var BABYLON;
  45367. (function (BABYLON) {
  45368. var AnimationRange = /** @class */ (function () {
  45369. function AnimationRange(name, from, to) {
  45370. this.name = name;
  45371. this.from = from;
  45372. this.to = to;
  45373. }
  45374. AnimationRange.prototype.clone = function () {
  45375. return new AnimationRange(this.name, this.from, this.to);
  45376. };
  45377. return AnimationRange;
  45378. }());
  45379. BABYLON.AnimationRange = AnimationRange;
  45380. /**
  45381. * Composed of a frame, and an action function
  45382. */
  45383. var AnimationEvent = /** @class */ (function () {
  45384. function AnimationEvent(frame, action, onlyOnce) {
  45385. this.frame = frame;
  45386. this.action = action;
  45387. this.onlyOnce = onlyOnce;
  45388. this.isDone = false;
  45389. }
  45390. return AnimationEvent;
  45391. }());
  45392. BABYLON.AnimationEvent = AnimationEvent;
  45393. var PathCursor = /** @class */ (function () {
  45394. function PathCursor(path) {
  45395. this.path = path;
  45396. this._onchange = new Array();
  45397. this.value = 0;
  45398. this.animations = new Array();
  45399. }
  45400. PathCursor.prototype.getPoint = function () {
  45401. var point = this.path.getPointAtLengthPosition(this.value);
  45402. return new BABYLON.Vector3(point.x, 0, point.y);
  45403. };
  45404. PathCursor.prototype.moveAhead = function (step) {
  45405. if (step === void 0) { step = 0.002; }
  45406. this.move(step);
  45407. return this;
  45408. };
  45409. PathCursor.prototype.moveBack = function (step) {
  45410. if (step === void 0) { step = 0.002; }
  45411. this.move(-step);
  45412. return this;
  45413. };
  45414. PathCursor.prototype.move = function (step) {
  45415. if (Math.abs(step) > 1) {
  45416. throw "step size should be less than 1.";
  45417. }
  45418. this.value += step;
  45419. this.ensureLimits();
  45420. this.raiseOnChange();
  45421. return this;
  45422. };
  45423. PathCursor.prototype.ensureLimits = function () {
  45424. while (this.value > 1) {
  45425. this.value -= 1;
  45426. }
  45427. while (this.value < 0) {
  45428. this.value += 1;
  45429. }
  45430. return this;
  45431. };
  45432. // used by animation engine
  45433. PathCursor.prototype.raiseOnChange = function () {
  45434. var _this = this;
  45435. this._onchange.forEach(function (f) { return f(_this); });
  45436. return this;
  45437. };
  45438. PathCursor.prototype.onchange = function (f) {
  45439. this._onchange.push(f);
  45440. return this;
  45441. };
  45442. return PathCursor;
  45443. }());
  45444. BABYLON.PathCursor = PathCursor;
  45445. var AnimationKeyInterpolation;
  45446. (function (AnimationKeyInterpolation) {
  45447. /**
  45448. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45449. */
  45450. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45451. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45452. var Animation = /** @class */ (function () {
  45453. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45454. this.name = name;
  45455. this.targetProperty = targetProperty;
  45456. this.framePerSecond = framePerSecond;
  45457. this.dataType = dataType;
  45458. this.loopMode = loopMode;
  45459. this.enableBlending = enableBlending;
  45460. this._runtimeAnimations = new Array();
  45461. // The set of event that will be linked to this animation
  45462. this._events = new Array();
  45463. this.blendingSpeed = 0.01;
  45464. this._ranges = {};
  45465. this.targetPropertyPath = targetProperty.split(".");
  45466. this.dataType = dataType;
  45467. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45468. }
  45469. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45470. var dataType = undefined;
  45471. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45472. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45473. }
  45474. else if (from instanceof BABYLON.Quaternion) {
  45475. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45476. }
  45477. else if (from instanceof BABYLON.Vector3) {
  45478. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45479. }
  45480. else if (from instanceof BABYLON.Vector2) {
  45481. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45482. }
  45483. else if (from instanceof BABYLON.Color3) {
  45484. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45485. }
  45486. else if (from instanceof BABYLON.Size) {
  45487. dataType = Animation.ANIMATIONTYPE_SIZE;
  45488. }
  45489. if (dataType == undefined) {
  45490. return null;
  45491. }
  45492. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45493. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45494. animation.setKeys(keys);
  45495. if (easingFunction !== undefined) {
  45496. animation.setEasingFunction(easingFunction);
  45497. }
  45498. return animation;
  45499. };
  45500. /**
  45501. * Sets up an animation.
  45502. * @param property the property to animate
  45503. * @param animationType the animation type to apply
  45504. * @param easingFunction the easing function used in the animation
  45505. * @returns The created animation
  45506. */
  45507. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45508. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45509. animation.setEasingFunction(easingFunction);
  45510. return animation;
  45511. };
  45512. /**
  45513. * Create and start an animation on a node
  45514. * @param {string} name defines the name of the global animation that will be run on all nodes
  45515. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45516. * @param {string} targetProperty defines property to animate
  45517. * @param {number} framePerSecond defines the number of frame per second yo use
  45518. * @param {number} totalFrame defines the number of frames in total
  45519. * @param {any} from defines the initial value
  45520. * @param {any} to defines the final value
  45521. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45522. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45523. * @param onAnimationEnd defines the callback to call when animation end
  45524. * @returns the animatable created for this animation
  45525. */
  45526. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45527. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45528. if (!animation) {
  45529. return null;
  45530. }
  45531. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45532. };
  45533. /**
  45534. * Create and start an animation on a node and its descendants
  45535. * @param {string} name defines the name of the global animation that will be run on all nodes
  45536. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45537. * @param {boolean} 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.
  45538. * @param {string} targetProperty defines property to animate
  45539. * @param {number} framePerSecond defines the number of frame per second yo use
  45540. * @param {number} totalFrame defines the number of frames in total
  45541. * @param {any} from defines the initial value
  45542. * @param {any} to defines the final value
  45543. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45544. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45545. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45546. * @returns the list of animatables created for all nodes
  45547. * @example https://www.babylonjs-playground.com/#MH0VLI
  45548. */
  45549. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45550. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45551. if (!animation) {
  45552. return null;
  45553. }
  45554. var scene = node.getScene();
  45555. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45556. };
  45557. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45558. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45559. if (!animation) {
  45560. return null;
  45561. }
  45562. node.animations.push(animation);
  45563. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45564. };
  45565. /**
  45566. * Transition property of the Camera to the target Value.
  45567. * @param property The property to transition
  45568. * @param targetValue The target Value of the property
  45569. * @param host The object where the property to animate belongs
  45570. * @param scene Scene used to run the animation
  45571. * @param frameRate Framerate (in frame/s) to use
  45572. * @param transition The transition type we want to use
  45573. * @param duration The duration of the animation, in milliseconds
  45574. * @param onAnimationEnd Call back trigger at the end of the animation.
  45575. */
  45576. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45577. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45578. if (duration <= 0) {
  45579. host[property] = targetValue;
  45580. if (onAnimationEnd) {
  45581. onAnimationEnd();
  45582. }
  45583. return null;
  45584. }
  45585. var endFrame = frameRate * (duration / 1000);
  45586. transition.setKeys([{
  45587. frame: 0,
  45588. value: host[property].clone ? host[property].clone() : host[property]
  45589. },
  45590. {
  45591. frame: endFrame,
  45592. value: targetValue
  45593. }]);
  45594. if (!host.animations) {
  45595. host.animations = [];
  45596. }
  45597. host.animations.push(transition);
  45598. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45599. animation.onAnimationEnd = onAnimationEnd;
  45600. return animation;
  45601. };
  45602. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45603. /**
  45604. * Return the array of runtime animations currently using this animation
  45605. */
  45606. get: function () {
  45607. return this._runtimeAnimations;
  45608. },
  45609. enumerable: true,
  45610. configurable: true
  45611. });
  45612. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45613. get: function () {
  45614. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  45615. var runtimeAnimation = _a[_i];
  45616. if (!runtimeAnimation.isStopped) {
  45617. return true;
  45618. }
  45619. }
  45620. return false;
  45621. },
  45622. enumerable: true,
  45623. configurable: true
  45624. });
  45625. // Methods
  45626. /**
  45627. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  45628. */
  45629. Animation.prototype.toString = function (fullDetails) {
  45630. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  45631. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  45632. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  45633. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  45634. if (fullDetails) {
  45635. ret += ", Ranges: {";
  45636. var first = true;
  45637. for (var name in this._ranges) {
  45638. if (first) {
  45639. ret += ", ";
  45640. first = false;
  45641. }
  45642. ret += name;
  45643. }
  45644. ret += "}";
  45645. }
  45646. return ret;
  45647. };
  45648. /**
  45649. * Add an event to this animation.
  45650. */
  45651. Animation.prototype.addEvent = function (event) {
  45652. this._events.push(event);
  45653. };
  45654. /**
  45655. * Remove all events found at the given frame
  45656. * @param frame
  45657. */
  45658. Animation.prototype.removeEvents = function (frame) {
  45659. for (var index = 0; index < this._events.length; index++) {
  45660. if (this._events[index].frame === frame) {
  45661. this._events.splice(index, 1);
  45662. index--;
  45663. }
  45664. }
  45665. };
  45666. Animation.prototype.getEvents = function () {
  45667. return this._events;
  45668. };
  45669. Animation.prototype.createRange = function (name, from, to) {
  45670. // check name not already in use; could happen for bones after serialized
  45671. if (!this._ranges[name]) {
  45672. this._ranges[name] = new AnimationRange(name, from, to);
  45673. }
  45674. };
  45675. Animation.prototype.deleteRange = function (name, deleteFrames) {
  45676. if (deleteFrames === void 0) { deleteFrames = true; }
  45677. var range = this._ranges[name];
  45678. if (!range) {
  45679. return;
  45680. }
  45681. if (deleteFrames) {
  45682. var from = range.from;
  45683. var to = range.to;
  45684. // this loop MUST go high to low for multiple splices to work
  45685. for (var key = this._keys.length - 1; key >= 0; key--) {
  45686. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  45687. this._keys.splice(key, 1);
  45688. }
  45689. }
  45690. }
  45691. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  45692. };
  45693. Animation.prototype.getRange = function (name) {
  45694. return this._ranges[name];
  45695. };
  45696. Animation.prototype.getKeys = function () {
  45697. return this._keys;
  45698. };
  45699. Animation.prototype.getHighestFrame = function () {
  45700. var ret = 0;
  45701. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  45702. if (ret < this._keys[key].frame) {
  45703. ret = this._keys[key].frame;
  45704. }
  45705. }
  45706. return ret;
  45707. };
  45708. Animation.prototype.getEasingFunction = function () {
  45709. return this._easingFunction;
  45710. };
  45711. Animation.prototype.setEasingFunction = function (easingFunction) {
  45712. this._easingFunction = easingFunction;
  45713. };
  45714. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  45715. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  45716. };
  45717. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45718. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45719. };
  45720. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  45721. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  45722. };
  45723. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45724. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  45725. };
  45726. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  45727. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  45728. };
  45729. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45730. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45731. };
  45732. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  45733. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  45734. };
  45735. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45736. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45737. };
  45738. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  45739. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  45740. };
  45741. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  45742. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  45743. };
  45744. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  45745. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  45746. };
  45747. Animation.prototype.clone = function () {
  45748. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  45749. clone.enableBlending = this.enableBlending;
  45750. clone.blendingSpeed = this.blendingSpeed;
  45751. if (this._keys) {
  45752. clone.setKeys(this._keys);
  45753. }
  45754. if (this._ranges) {
  45755. clone._ranges = {};
  45756. for (var name in this._ranges) {
  45757. var range = this._ranges[name];
  45758. if (!range) {
  45759. continue;
  45760. }
  45761. clone._ranges[name] = range.clone();
  45762. }
  45763. }
  45764. return clone;
  45765. };
  45766. Animation.prototype.setKeys = function (values) {
  45767. this._keys = values.slice(0);
  45768. };
  45769. Animation.prototype.serialize = function () {
  45770. var serializationObject = {};
  45771. serializationObject.name = this.name;
  45772. serializationObject.property = this.targetProperty;
  45773. serializationObject.framePerSecond = this.framePerSecond;
  45774. serializationObject.dataType = this.dataType;
  45775. serializationObject.loopBehavior = this.loopMode;
  45776. serializationObject.enableBlending = this.enableBlending;
  45777. serializationObject.blendingSpeed = this.blendingSpeed;
  45778. var dataType = this.dataType;
  45779. serializationObject.keys = [];
  45780. var keys = this.getKeys();
  45781. for (var index = 0; index < keys.length; index++) {
  45782. var animationKey = keys[index];
  45783. var key = {};
  45784. key.frame = animationKey.frame;
  45785. switch (dataType) {
  45786. case Animation.ANIMATIONTYPE_FLOAT:
  45787. key.values = [animationKey.value];
  45788. break;
  45789. case Animation.ANIMATIONTYPE_QUATERNION:
  45790. case Animation.ANIMATIONTYPE_MATRIX:
  45791. case Animation.ANIMATIONTYPE_VECTOR3:
  45792. case Animation.ANIMATIONTYPE_COLOR3:
  45793. key.values = animationKey.value.asArray();
  45794. break;
  45795. }
  45796. serializationObject.keys.push(key);
  45797. }
  45798. serializationObject.ranges = [];
  45799. for (var name in this._ranges) {
  45800. var source = this._ranges[name];
  45801. if (!source) {
  45802. continue;
  45803. }
  45804. var range = {};
  45805. range.name = name;
  45806. range.from = source.from;
  45807. range.to = source.to;
  45808. serializationObject.ranges.push(range);
  45809. }
  45810. return serializationObject;
  45811. };
  45812. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  45813. get: function () {
  45814. return Animation._ANIMATIONTYPE_FLOAT;
  45815. },
  45816. enumerable: true,
  45817. configurable: true
  45818. });
  45819. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  45820. get: function () {
  45821. return Animation._ANIMATIONTYPE_VECTOR3;
  45822. },
  45823. enumerable: true,
  45824. configurable: true
  45825. });
  45826. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  45827. get: function () {
  45828. return Animation._ANIMATIONTYPE_VECTOR2;
  45829. },
  45830. enumerable: true,
  45831. configurable: true
  45832. });
  45833. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  45834. get: function () {
  45835. return Animation._ANIMATIONTYPE_SIZE;
  45836. },
  45837. enumerable: true,
  45838. configurable: true
  45839. });
  45840. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  45841. get: function () {
  45842. return Animation._ANIMATIONTYPE_QUATERNION;
  45843. },
  45844. enumerable: true,
  45845. configurable: true
  45846. });
  45847. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  45848. get: function () {
  45849. return Animation._ANIMATIONTYPE_MATRIX;
  45850. },
  45851. enumerable: true,
  45852. configurable: true
  45853. });
  45854. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  45855. get: function () {
  45856. return Animation._ANIMATIONTYPE_COLOR3;
  45857. },
  45858. enumerable: true,
  45859. configurable: true
  45860. });
  45861. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  45862. get: function () {
  45863. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  45864. },
  45865. enumerable: true,
  45866. configurable: true
  45867. });
  45868. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  45869. get: function () {
  45870. return Animation._ANIMATIONLOOPMODE_CYCLE;
  45871. },
  45872. enumerable: true,
  45873. configurable: true
  45874. });
  45875. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  45876. get: function () {
  45877. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  45878. },
  45879. enumerable: true,
  45880. configurable: true
  45881. });
  45882. Animation.Parse = function (parsedAnimation) {
  45883. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  45884. var dataType = parsedAnimation.dataType;
  45885. var keys = [];
  45886. var data;
  45887. var index;
  45888. if (parsedAnimation.enableBlending) {
  45889. animation.enableBlending = parsedAnimation.enableBlending;
  45890. }
  45891. if (parsedAnimation.blendingSpeed) {
  45892. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  45893. }
  45894. for (index = 0; index < parsedAnimation.keys.length; index++) {
  45895. var key = parsedAnimation.keys[index];
  45896. var inTangent;
  45897. var outTangent;
  45898. switch (dataType) {
  45899. case Animation.ANIMATIONTYPE_FLOAT:
  45900. data = key.values[0];
  45901. if (key.values.length >= 1) {
  45902. inTangent = key.values[1];
  45903. }
  45904. if (key.values.length >= 2) {
  45905. outTangent = key.values[2];
  45906. }
  45907. break;
  45908. case Animation.ANIMATIONTYPE_QUATERNION:
  45909. data = BABYLON.Quaternion.FromArray(key.values);
  45910. if (key.values.length >= 8) {
  45911. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  45912. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  45913. inTangent = _inTangent;
  45914. }
  45915. }
  45916. if (key.values.length >= 12) {
  45917. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  45918. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  45919. outTangent = _outTangent;
  45920. }
  45921. }
  45922. break;
  45923. case Animation.ANIMATIONTYPE_MATRIX:
  45924. data = BABYLON.Matrix.FromArray(key.values);
  45925. break;
  45926. case Animation.ANIMATIONTYPE_COLOR3:
  45927. data = BABYLON.Color3.FromArray(key.values);
  45928. break;
  45929. case Animation.ANIMATIONTYPE_VECTOR3:
  45930. default:
  45931. data = BABYLON.Vector3.FromArray(key.values);
  45932. break;
  45933. }
  45934. var keyData = {};
  45935. keyData.frame = key.frame;
  45936. keyData.value = data;
  45937. if (inTangent != undefined) {
  45938. keyData.inTangent = inTangent;
  45939. }
  45940. if (outTangent != undefined) {
  45941. keyData.outTangent = outTangent;
  45942. }
  45943. keys.push(keyData);
  45944. }
  45945. animation.setKeys(keys);
  45946. if (parsedAnimation.ranges) {
  45947. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  45948. data = parsedAnimation.ranges[index];
  45949. animation.createRange(data.name, data.from, data.to);
  45950. }
  45951. }
  45952. return animation;
  45953. };
  45954. Animation.AppendSerializedAnimations = function (source, destination) {
  45955. if (source.animations) {
  45956. destination.animations = [];
  45957. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  45958. var animation = source.animations[animationIndex];
  45959. destination.animations.push(animation.serialize());
  45960. }
  45961. }
  45962. };
  45963. Animation.AllowMatricesInterpolation = false;
  45964. // Statics
  45965. Animation._ANIMATIONTYPE_FLOAT = 0;
  45966. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  45967. Animation._ANIMATIONTYPE_QUATERNION = 2;
  45968. Animation._ANIMATIONTYPE_MATRIX = 3;
  45969. Animation._ANIMATIONTYPE_COLOR3 = 4;
  45970. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  45971. Animation._ANIMATIONTYPE_SIZE = 6;
  45972. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  45973. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  45974. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  45975. return Animation;
  45976. }());
  45977. BABYLON.Animation = Animation;
  45978. })(BABYLON || (BABYLON = {}));
  45979. //# sourceMappingURL=babylon.animation.js.map
  45980. var BABYLON;
  45981. (function (BABYLON) {
  45982. /**
  45983. * This class defines the direct association between an animation and a target
  45984. */
  45985. var TargetedAnimation = /** @class */ (function () {
  45986. function TargetedAnimation() {
  45987. }
  45988. return TargetedAnimation;
  45989. }());
  45990. BABYLON.TargetedAnimation = TargetedAnimation;
  45991. /**
  45992. * Use this class to create coordinated animations on multiple targets
  45993. */
  45994. var AnimationGroup = /** @class */ (function () {
  45995. function AnimationGroup(name, scene) {
  45996. if (scene === void 0) { scene = null; }
  45997. this.name = name;
  45998. this._targetedAnimations = new Array();
  45999. this._animatables = new Array();
  46000. this._from = Number.MAX_VALUE;
  46001. this._to = -Number.MAX_VALUE;
  46002. this._speedRatio = 1;
  46003. this.onAnimationEndObservable = new BABYLON.Observable();
  46004. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46005. this._scene.animationGroups.push(this);
  46006. }
  46007. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46008. /**
  46009. * Define if the animations are started
  46010. */
  46011. get: function () {
  46012. return this._isStarted;
  46013. },
  46014. enumerable: true,
  46015. configurable: true
  46016. });
  46017. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46018. /**
  46019. * Gets or sets the speed ratio to use for all animations
  46020. */
  46021. get: function () {
  46022. return this._speedRatio;
  46023. },
  46024. /**
  46025. * Gets or sets the speed ratio to use for all animations
  46026. */
  46027. set: function (value) {
  46028. if (this._speedRatio === value) {
  46029. return;
  46030. }
  46031. this._speedRatio = value;
  46032. for (var index = 0; index < this._animatables.length; index++) {
  46033. var animatable = this._animatables[index];
  46034. animatable.speedRatio = this._speedRatio;
  46035. }
  46036. },
  46037. enumerable: true,
  46038. configurable: true
  46039. });
  46040. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46041. /**
  46042. * Gets the targeted animations for this animation group
  46043. */
  46044. get: function () {
  46045. return this._targetedAnimations;
  46046. },
  46047. enumerable: true,
  46048. configurable: true
  46049. });
  46050. /**
  46051. * Add an animation (with its target) in the group
  46052. * @param animation defines the animation we want to add
  46053. * @param target defines the target of the animation
  46054. * @returns the {BABYLON.TargetedAnimation} object
  46055. */
  46056. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46057. var targetedAnimation = {
  46058. animation: animation,
  46059. target: target
  46060. };
  46061. var keys = animation.getKeys();
  46062. if (this._from > keys[0].frame) {
  46063. this._from = keys[0].frame;
  46064. }
  46065. if (this._to < keys[keys.length - 1].frame) {
  46066. this._to = keys[keys.length - 1].frame;
  46067. }
  46068. this._targetedAnimations.push(targetedAnimation);
  46069. return targetedAnimation;
  46070. };
  46071. /**
  46072. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46073. * It can add constant keys at begin or end
  46074. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46075. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46076. */
  46077. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46078. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46079. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46080. beginFrame = Math.max(beginFrame, this._from);
  46081. endFrame = Math.min(endFrame, this._to);
  46082. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46083. var targetedAnimation = this._targetedAnimations[index];
  46084. var keys = targetedAnimation.animation.getKeys();
  46085. var startKey = keys[0];
  46086. var endKey = keys[keys.length - 1];
  46087. if (startKey.frame > beginFrame) {
  46088. var newKey = {
  46089. frame: beginFrame,
  46090. value: startKey.value,
  46091. inTangent: startKey.inTangent,
  46092. outTangent: startKey.outTangent,
  46093. interpolation: startKey.interpolation
  46094. };
  46095. keys.splice(0, 0, newKey);
  46096. }
  46097. if (endKey.frame < endFrame) {
  46098. var newKey = {
  46099. frame: endFrame,
  46100. value: endKey.value,
  46101. inTangent: endKey.outTangent,
  46102. outTangent: endKey.outTangent,
  46103. interpolation: endKey.interpolation
  46104. };
  46105. keys.push(newKey);
  46106. }
  46107. }
  46108. return this;
  46109. };
  46110. /**
  46111. * Start all animations on given targets
  46112. * @param loop defines if animations must loop
  46113. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46114. */
  46115. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46116. var _this = this;
  46117. if (loop === void 0) { loop = false; }
  46118. if (speedRatio === void 0) { speedRatio = 1; }
  46119. if (this._isStarted || this._targetedAnimations.length === 0) {
  46120. return this;
  46121. }
  46122. var _loop_1 = function () {
  46123. var targetedAnimation = this_1._targetedAnimations[index];
  46124. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46125. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46126. }));
  46127. };
  46128. var this_1 = this;
  46129. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46130. _loop_1();
  46131. }
  46132. this._speedRatio = speedRatio;
  46133. this._isStarted = true;
  46134. return this;
  46135. };
  46136. /**
  46137. * Pause all animations
  46138. */
  46139. AnimationGroup.prototype.pause = function () {
  46140. if (!this._isStarted) {
  46141. return this;
  46142. }
  46143. for (var index = 0; index < this._animatables.length; index++) {
  46144. var animatable = this._animatables[index];
  46145. animatable.pause();
  46146. }
  46147. return this;
  46148. };
  46149. /**
  46150. * Play all animations to initial state
  46151. * This function will start() the animations if they were not started or will restart() them if they were paused
  46152. * @param loop defines if animations must loop
  46153. */
  46154. AnimationGroup.prototype.play = function (loop) {
  46155. if (this.isStarted) {
  46156. if (loop !== undefined) {
  46157. for (var index = 0; index < this._animatables.length; index++) {
  46158. var animatable = this._animatables[index];
  46159. animatable.loopAnimation = loop;
  46160. }
  46161. }
  46162. this.restart();
  46163. }
  46164. else {
  46165. this.start(loop, this._speedRatio);
  46166. }
  46167. return this;
  46168. };
  46169. /**
  46170. * Reset all animations to initial state
  46171. */
  46172. AnimationGroup.prototype.reset = function () {
  46173. if (!this._isStarted) {
  46174. return this;
  46175. }
  46176. for (var index = 0; index < this._animatables.length; index++) {
  46177. var animatable = this._animatables[index];
  46178. animatable.reset();
  46179. }
  46180. return this;
  46181. };
  46182. /**
  46183. * Restart animations from key 0
  46184. */
  46185. AnimationGroup.prototype.restart = function () {
  46186. if (!this._isStarted) {
  46187. return this;
  46188. }
  46189. for (var index = 0; index < this._animatables.length; index++) {
  46190. var animatable = this._animatables[index];
  46191. animatable.restart();
  46192. }
  46193. return this;
  46194. };
  46195. /**
  46196. * Stop all animations
  46197. */
  46198. AnimationGroup.prototype.stop = function () {
  46199. if (!this._isStarted) {
  46200. return this;
  46201. }
  46202. for (var index = 0; index < this._animatables.length; index++) {
  46203. var animatable = this._animatables[index];
  46204. animatable.stop();
  46205. }
  46206. this._isStarted = false;
  46207. return this;
  46208. };
  46209. /**
  46210. * Dispose all associated resources
  46211. */
  46212. AnimationGroup.prototype.dispose = function () {
  46213. this._targetedAnimations = [];
  46214. this._animatables = [];
  46215. var index = this._scene.animationGroups.indexOf(this);
  46216. if (index > -1) {
  46217. this._scene.animationGroups.splice(index, 1);
  46218. }
  46219. };
  46220. return AnimationGroup;
  46221. }());
  46222. BABYLON.AnimationGroup = AnimationGroup;
  46223. })(BABYLON || (BABYLON = {}));
  46224. //# sourceMappingURL=babylon.animationGroup.js.map
  46225. var BABYLON;
  46226. (function (BABYLON) {
  46227. var RuntimeAnimation = /** @class */ (function () {
  46228. function RuntimeAnimation(target, animation) {
  46229. this._offsetsCache = {};
  46230. this._highLimitsCache = {};
  46231. this._stopped = false;
  46232. this._blendingFactor = 0;
  46233. this._ratioOffset = 0;
  46234. this._animation = animation;
  46235. this._target = target;
  46236. animation._runtimeAnimations.push(this);
  46237. }
  46238. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46239. get: function () {
  46240. return this._animation;
  46241. },
  46242. enumerable: true,
  46243. configurable: true
  46244. });
  46245. RuntimeAnimation.prototype.reset = function () {
  46246. this._offsetsCache = {};
  46247. this._highLimitsCache = {};
  46248. this.currentFrame = 0;
  46249. this._blendingFactor = 0;
  46250. this._originalBlendValue = null;
  46251. };
  46252. RuntimeAnimation.prototype.isStopped = function () {
  46253. return this._stopped;
  46254. };
  46255. RuntimeAnimation.prototype.dispose = function () {
  46256. var index = this._animation.runtimeAnimations.indexOf(this);
  46257. if (index > -1) {
  46258. this._animation.runtimeAnimations.splice(index, 1);
  46259. }
  46260. };
  46261. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46262. if (typeof value === "function") {
  46263. return value();
  46264. }
  46265. return value;
  46266. };
  46267. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46268. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46269. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46270. }
  46271. this.currentFrame = currentFrame;
  46272. var keys = this._animation.getKeys();
  46273. // Try to get a hash to find the right key
  46274. 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));
  46275. if (keys[startKeyIndex].frame >= currentFrame) {
  46276. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46277. startKeyIndex--;
  46278. }
  46279. }
  46280. for (var key = startKeyIndex; key < keys.length; key++) {
  46281. var endKey = keys[key + 1];
  46282. if (endKey.frame >= currentFrame) {
  46283. var startKey = keys[key];
  46284. var startValue = this._getKeyValue(startKey.value);
  46285. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46286. return startValue;
  46287. }
  46288. var endValue = this._getKeyValue(endKey.value);
  46289. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46290. var frameDelta = endKey.frame - startKey.frame;
  46291. // gradient : percent of currentFrame between the frame inf and the frame sup
  46292. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46293. // check for easingFunction and correction of gradient
  46294. var easingFunction = this._animation.getEasingFunction();
  46295. if (easingFunction != null) {
  46296. gradient = easingFunction.ease(gradient);
  46297. }
  46298. switch (this._animation.dataType) {
  46299. // Float
  46300. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46301. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46302. switch (loopMode) {
  46303. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46304. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46305. return floatValue;
  46306. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46307. return offsetValue * repeatCount + floatValue;
  46308. }
  46309. break;
  46310. // Quaternion
  46311. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46312. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46313. switch (loopMode) {
  46314. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46315. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46316. return quatValue;
  46317. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46318. return quatValue.add(offsetValue.scale(repeatCount));
  46319. }
  46320. return quatValue;
  46321. // Vector3
  46322. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46323. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46324. switch (loopMode) {
  46325. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46326. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46327. return vec3Value;
  46328. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46329. return vec3Value.add(offsetValue.scale(repeatCount));
  46330. }
  46331. // Vector2
  46332. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46333. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46334. switch (loopMode) {
  46335. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46336. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46337. return vec2Value;
  46338. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46339. return vec2Value.add(offsetValue.scale(repeatCount));
  46340. }
  46341. // Size
  46342. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46343. switch (loopMode) {
  46344. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46345. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46346. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46347. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46348. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46349. }
  46350. // Color3
  46351. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46352. switch (loopMode) {
  46353. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46354. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46355. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46356. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46357. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46358. }
  46359. // Matrix
  46360. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46361. switch (loopMode) {
  46362. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46363. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46364. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46365. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46366. }
  46367. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46368. return startValue;
  46369. }
  46370. default:
  46371. break;
  46372. }
  46373. break;
  46374. }
  46375. }
  46376. return this._getKeyValue(keys[keys.length - 1].value);
  46377. };
  46378. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46379. if (blend === void 0) { blend = false; }
  46380. // Set value
  46381. var path;
  46382. var destination;
  46383. var targetPropertyPath = this._animation.targetPropertyPath;
  46384. if (targetPropertyPath.length > 1) {
  46385. var property = this._target[targetPropertyPath[0]];
  46386. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46387. property = property[targetPropertyPath[index]];
  46388. }
  46389. path = targetPropertyPath[targetPropertyPath.length - 1];
  46390. destination = property;
  46391. }
  46392. else {
  46393. path = targetPropertyPath[0];
  46394. destination = this._target;
  46395. }
  46396. // Blending
  46397. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46398. if (!this._originalBlendValue) {
  46399. if (destination[path].clone) {
  46400. this._originalBlendValue = destination[path].clone();
  46401. }
  46402. else {
  46403. this._originalBlendValue = destination[path];
  46404. }
  46405. }
  46406. if (this._originalBlendValue.prototype) {
  46407. if (this._originalBlendValue.prototype.Lerp) {
  46408. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46409. }
  46410. else {
  46411. destination[path] = currentValue;
  46412. }
  46413. }
  46414. else if (this._originalBlendValue.m) {
  46415. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46416. }
  46417. else {
  46418. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46419. }
  46420. this._blendingFactor += this._animation.blendingSpeed;
  46421. }
  46422. else {
  46423. destination[path] = currentValue;
  46424. }
  46425. if (this._target.markAsDirty) {
  46426. this._target.markAsDirty(this._animation.targetProperty);
  46427. }
  46428. };
  46429. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46430. var keys = this._animation.getKeys();
  46431. if (frame < keys[0].frame) {
  46432. frame = keys[0].frame;
  46433. }
  46434. else if (frame > keys[keys.length - 1].frame) {
  46435. frame = keys[keys.length - 1].frame;
  46436. }
  46437. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46438. this.setValue(currentValue);
  46439. };
  46440. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46441. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46442. this._ratioOffset = this._previousRatio - newRatio;
  46443. };
  46444. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46445. if (blend === void 0) { blend = false; }
  46446. var targetPropertyPath = this._animation.targetPropertyPath;
  46447. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46448. this._stopped = true;
  46449. return false;
  46450. }
  46451. var returnValue = true;
  46452. var keys = this._animation.getKeys();
  46453. // Adding a start key at frame 0 if missing
  46454. if (keys[0].frame !== 0) {
  46455. var newKey = { frame: 0, value: keys[0].value };
  46456. keys.splice(0, 0, newKey);
  46457. }
  46458. // Check limits
  46459. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46460. from = keys[0].frame;
  46461. }
  46462. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46463. to = keys[keys.length - 1].frame;
  46464. }
  46465. //to and from cannot be the same key
  46466. if (from === to) {
  46467. if (from > keys[0].frame) {
  46468. from--;
  46469. }
  46470. else if (to < keys[keys.length - 1].frame) {
  46471. to++;
  46472. }
  46473. }
  46474. // Compute ratio
  46475. var range = to - from;
  46476. var offsetValue;
  46477. // ratio represents the frame delta between from and to
  46478. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46479. var highLimitValue = 0;
  46480. this._previousDelay = delay;
  46481. this._previousRatio = ratio;
  46482. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46483. returnValue = false;
  46484. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46485. }
  46486. else {
  46487. // Get max value if required
  46488. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46489. var keyOffset = to.toString() + from.toString();
  46490. if (!this._offsetsCache[keyOffset]) {
  46491. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46492. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46493. switch (this._animation.dataType) {
  46494. // Float
  46495. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46496. this._offsetsCache[keyOffset] = toValue - fromValue;
  46497. break;
  46498. // Quaternion
  46499. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46500. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46501. break;
  46502. // Vector3
  46503. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46504. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46505. // Vector2
  46506. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46507. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46508. // Size
  46509. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46510. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46511. // Color3
  46512. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46513. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46514. default:
  46515. break;
  46516. }
  46517. this._highLimitsCache[keyOffset] = toValue;
  46518. }
  46519. highLimitValue = this._highLimitsCache[keyOffset];
  46520. offsetValue = this._offsetsCache[keyOffset];
  46521. }
  46522. }
  46523. if (offsetValue === undefined) {
  46524. switch (this._animation.dataType) {
  46525. // Float
  46526. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46527. offsetValue = 0;
  46528. break;
  46529. // Quaternion
  46530. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46531. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46532. break;
  46533. // Vector3
  46534. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46535. offsetValue = BABYLON.Vector3.Zero();
  46536. break;
  46537. // Vector2
  46538. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46539. offsetValue = BABYLON.Vector2.Zero();
  46540. break;
  46541. // Size
  46542. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46543. offsetValue = BABYLON.Size.Zero();
  46544. break;
  46545. // Color3
  46546. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46547. offsetValue = BABYLON.Color3.Black();
  46548. }
  46549. }
  46550. // Compute value
  46551. var repeatCount = (ratio / range) >> 0;
  46552. var currentFrame = returnValue ? from + ratio % range : to;
  46553. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46554. // Set value
  46555. this.setValue(currentValue);
  46556. // Check events
  46557. var events = this._animation.getEvents();
  46558. for (var index = 0; index < events.length; index++) {
  46559. // Make sure current frame has passed event frame and that event frame is within the current range
  46560. // Also, handle both forward and reverse animations
  46561. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46562. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46563. var event = events[index];
  46564. if (!event.isDone) {
  46565. // If event should be done only once, remove it.
  46566. if (event.onlyOnce) {
  46567. events.splice(index, 1);
  46568. index--;
  46569. }
  46570. event.isDone = true;
  46571. event.action();
  46572. } // Don't do anything if the event has already be done.
  46573. }
  46574. else if (events[index].isDone && !events[index].onlyOnce) {
  46575. // reset event, the animation is looping
  46576. events[index].isDone = false;
  46577. }
  46578. }
  46579. if (!returnValue) {
  46580. this._stopped = true;
  46581. }
  46582. return returnValue;
  46583. };
  46584. return RuntimeAnimation;
  46585. }());
  46586. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46587. })(BABYLON || (BABYLON = {}));
  46588. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46589. var BABYLON;
  46590. (function (BABYLON) {
  46591. var Animatable = /** @class */ (function () {
  46592. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46593. if (fromFrame === void 0) { fromFrame = 0; }
  46594. if (toFrame === void 0) { toFrame = 100; }
  46595. if (loopAnimation === void 0) { loopAnimation = false; }
  46596. if (speedRatio === void 0) { speedRatio = 1.0; }
  46597. this.target = target;
  46598. this.fromFrame = fromFrame;
  46599. this.toFrame = toFrame;
  46600. this.loopAnimation = loopAnimation;
  46601. this.onAnimationEnd = onAnimationEnd;
  46602. this._localDelayOffset = null;
  46603. this._pausedDelay = null;
  46604. this._runtimeAnimations = new Array();
  46605. this._paused = false;
  46606. this._speedRatio = 1;
  46607. this.animationStarted = false;
  46608. if (animations) {
  46609. this.appendAnimations(target, animations);
  46610. }
  46611. this._speedRatio = speedRatio;
  46612. this._scene = scene;
  46613. scene._activeAnimatables.push(this);
  46614. }
  46615. Object.defineProperty(Animatable.prototype, "speedRatio", {
  46616. get: function () {
  46617. return this._speedRatio;
  46618. },
  46619. set: function (value) {
  46620. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  46621. var animation = this._runtimeAnimations[index];
  46622. animation._prepareForSpeedRatioChange(value);
  46623. }
  46624. this._speedRatio = value;
  46625. },
  46626. enumerable: true,
  46627. configurable: true
  46628. });
  46629. // Methods
  46630. Animatable.prototype.getAnimations = function () {
  46631. return this._runtimeAnimations;
  46632. };
  46633. Animatable.prototype.appendAnimations = function (target, animations) {
  46634. for (var index = 0; index < animations.length; index++) {
  46635. var animation = animations[index];
  46636. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  46637. }
  46638. };
  46639. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  46640. var runtimeAnimations = this._runtimeAnimations;
  46641. for (var index = 0; index < runtimeAnimations.length; index++) {
  46642. if (runtimeAnimations[index].animation.targetProperty === property) {
  46643. return runtimeAnimations[index].animation;
  46644. }
  46645. }
  46646. return null;
  46647. };
  46648. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  46649. var runtimeAnimations = this._runtimeAnimations;
  46650. for (var index = 0; index < runtimeAnimations.length; index++) {
  46651. if (runtimeAnimations[index].animation.targetProperty === property) {
  46652. return runtimeAnimations[index];
  46653. }
  46654. }
  46655. return null;
  46656. };
  46657. Animatable.prototype.reset = function () {
  46658. var runtimeAnimations = this._runtimeAnimations;
  46659. for (var index = 0; index < runtimeAnimations.length; index++) {
  46660. runtimeAnimations[index].reset();
  46661. }
  46662. // Reset to original value
  46663. for (index = 0; index < runtimeAnimations.length; index++) {
  46664. var animation = runtimeAnimations[index];
  46665. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  46666. }
  46667. this._localDelayOffset = null;
  46668. this._pausedDelay = null;
  46669. };
  46670. Animatable.prototype.enableBlending = function (blendingSpeed) {
  46671. var runtimeAnimations = this._runtimeAnimations;
  46672. for (var index = 0; index < runtimeAnimations.length; index++) {
  46673. runtimeAnimations[index].animation.enableBlending = true;
  46674. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  46675. }
  46676. };
  46677. Animatable.prototype.disableBlending = function () {
  46678. var runtimeAnimations = this._runtimeAnimations;
  46679. for (var index = 0; index < runtimeAnimations.length; index++) {
  46680. runtimeAnimations[index].animation.enableBlending = false;
  46681. }
  46682. };
  46683. Animatable.prototype.goToFrame = function (frame) {
  46684. var runtimeAnimations = this._runtimeAnimations;
  46685. if (runtimeAnimations[0]) {
  46686. var fps = runtimeAnimations[0].animation.framePerSecond;
  46687. var currentFrame = runtimeAnimations[0].currentFrame;
  46688. var adjustTime = frame - currentFrame;
  46689. var delay = adjustTime * 1000 / fps;
  46690. if (this._localDelayOffset === null) {
  46691. this._localDelayOffset = 0;
  46692. }
  46693. this._localDelayOffset -= delay;
  46694. }
  46695. for (var index = 0; index < runtimeAnimations.length; index++) {
  46696. runtimeAnimations[index].goToFrame(frame);
  46697. }
  46698. };
  46699. Animatable.prototype.pause = function () {
  46700. if (this._paused) {
  46701. return;
  46702. }
  46703. this._paused = true;
  46704. };
  46705. Animatable.prototype.restart = function () {
  46706. this._paused = false;
  46707. };
  46708. Animatable.prototype.stop = function (animationName) {
  46709. if (animationName) {
  46710. var idx = this._scene._activeAnimatables.indexOf(this);
  46711. if (idx > -1) {
  46712. var runtimeAnimations = this._runtimeAnimations;
  46713. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  46714. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  46715. continue;
  46716. }
  46717. runtimeAnimations[index].dispose();
  46718. runtimeAnimations.splice(index, 1);
  46719. }
  46720. if (runtimeAnimations.length == 0) {
  46721. this._scene._activeAnimatables.splice(idx, 1);
  46722. if (this.onAnimationEnd) {
  46723. this.onAnimationEnd();
  46724. }
  46725. }
  46726. }
  46727. }
  46728. else {
  46729. var index = this._scene._activeAnimatables.indexOf(this);
  46730. if (index > -1) {
  46731. this._scene._activeAnimatables.splice(index, 1);
  46732. var runtimeAnimations = this._runtimeAnimations;
  46733. for (var index = 0; index < runtimeAnimations.length; index++) {
  46734. runtimeAnimations[index].dispose();
  46735. }
  46736. if (this.onAnimationEnd) {
  46737. this.onAnimationEnd();
  46738. }
  46739. }
  46740. }
  46741. };
  46742. Animatable.prototype._animate = function (delay) {
  46743. if (this._paused) {
  46744. this.animationStarted = false;
  46745. if (this._pausedDelay === null) {
  46746. this._pausedDelay = delay;
  46747. }
  46748. return true;
  46749. }
  46750. if (this._localDelayOffset === null) {
  46751. this._localDelayOffset = delay;
  46752. this._pausedDelay = null;
  46753. }
  46754. else if (this._pausedDelay !== null) {
  46755. this._localDelayOffset += delay - this._pausedDelay;
  46756. this._pausedDelay = null;
  46757. }
  46758. // Animating
  46759. var running = false;
  46760. var runtimeAnimations = this._runtimeAnimations;
  46761. var index;
  46762. for (index = 0; index < runtimeAnimations.length; index++) {
  46763. var animation = runtimeAnimations[index];
  46764. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  46765. running = running || isRunning;
  46766. }
  46767. this.animationStarted = running;
  46768. if (!running) {
  46769. // Remove from active animatables
  46770. index = this._scene._activeAnimatables.indexOf(this);
  46771. this._scene._activeAnimatables.splice(index, 1);
  46772. // Dispose all runtime animations
  46773. for (index = 0; index < runtimeAnimations.length; index++) {
  46774. runtimeAnimations[index].dispose();
  46775. }
  46776. }
  46777. if (!running && this.onAnimationEnd) {
  46778. this.onAnimationEnd();
  46779. this.onAnimationEnd = null;
  46780. }
  46781. return running;
  46782. };
  46783. return Animatable;
  46784. }());
  46785. BABYLON.Animatable = Animatable;
  46786. })(BABYLON || (BABYLON = {}));
  46787. //# sourceMappingURL=babylon.animatable.js.map
  46788. var BABYLON;
  46789. (function (BABYLON) {
  46790. var EasingFunction = /** @class */ (function () {
  46791. function EasingFunction() {
  46792. // Properties
  46793. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  46794. }
  46795. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  46796. get: function () {
  46797. return EasingFunction._EASINGMODE_EASEIN;
  46798. },
  46799. enumerable: true,
  46800. configurable: true
  46801. });
  46802. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  46803. get: function () {
  46804. return EasingFunction._EASINGMODE_EASEOUT;
  46805. },
  46806. enumerable: true,
  46807. configurable: true
  46808. });
  46809. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  46810. get: function () {
  46811. return EasingFunction._EASINGMODE_EASEINOUT;
  46812. },
  46813. enumerable: true,
  46814. configurable: true
  46815. });
  46816. EasingFunction.prototype.setEasingMode = function (easingMode) {
  46817. var n = Math.min(Math.max(easingMode, 0), 2);
  46818. this._easingMode = n;
  46819. };
  46820. EasingFunction.prototype.getEasingMode = function () {
  46821. return this._easingMode;
  46822. };
  46823. EasingFunction.prototype.easeInCore = function (gradient) {
  46824. throw new Error('You must implement this method');
  46825. };
  46826. EasingFunction.prototype.ease = function (gradient) {
  46827. switch (this._easingMode) {
  46828. case EasingFunction.EASINGMODE_EASEIN:
  46829. return this.easeInCore(gradient);
  46830. case EasingFunction.EASINGMODE_EASEOUT:
  46831. return (1 - this.easeInCore(1 - gradient));
  46832. }
  46833. if (gradient >= 0.5) {
  46834. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  46835. }
  46836. return (this.easeInCore(gradient * 2) * 0.5);
  46837. };
  46838. //Statics
  46839. EasingFunction._EASINGMODE_EASEIN = 0;
  46840. EasingFunction._EASINGMODE_EASEOUT = 1;
  46841. EasingFunction._EASINGMODE_EASEINOUT = 2;
  46842. return EasingFunction;
  46843. }());
  46844. BABYLON.EasingFunction = EasingFunction;
  46845. var CircleEase = /** @class */ (function (_super) {
  46846. __extends(CircleEase, _super);
  46847. function CircleEase() {
  46848. return _super !== null && _super.apply(this, arguments) || this;
  46849. }
  46850. CircleEase.prototype.easeInCore = function (gradient) {
  46851. gradient = Math.max(0, Math.min(1, gradient));
  46852. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  46853. };
  46854. return CircleEase;
  46855. }(EasingFunction));
  46856. BABYLON.CircleEase = CircleEase;
  46857. var BackEase = /** @class */ (function (_super) {
  46858. __extends(BackEase, _super);
  46859. function BackEase(amplitude) {
  46860. if (amplitude === void 0) { amplitude = 1; }
  46861. var _this = _super.call(this) || this;
  46862. _this.amplitude = amplitude;
  46863. return _this;
  46864. }
  46865. BackEase.prototype.easeInCore = function (gradient) {
  46866. var num = Math.max(0, this.amplitude);
  46867. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  46868. };
  46869. return BackEase;
  46870. }(EasingFunction));
  46871. BABYLON.BackEase = BackEase;
  46872. var BounceEase = /** @class */ (function (_super) {
  46873. __extends(BounceEase, _super);
  46874. function BounceEase(bounces, bounciness) {
  46875. if (bounces === void 0) { bounces = 3; }
  46876. if (bounciness === void 0) { bounciness = 2; }
  46877. var _this = _super.call(this) || this;
  46878. _this.bounces = bounces;
  46879. _this.bounciness = bounciness;
  46880. return _this;
  46881. }
  46882. BounceEase.prototype.easeInCore = function (gradient) {
  46883. var y = Math.max(0.0, this.bounces);
  46884. var bounciness = this.bounciness;
  46885. if (bounciness <= 1.0) {
  46886. bounciness = 1.001;
  46887. }
  46888. var num9 = Math.pow(bounciness, y);
  46889. var num5 = 1.0 - bounciness;
  46890. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  46891. var num15 = gradient * num4;
  46892. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  46893. var num3 = Math.floor(num65);
  46894. var num13 = num3 + 1.0;
  46895. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  46896. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  46897. var num7 = (num8 + num12) * 0.5;
  46898. var num6 = gradient - num7;
  46899. var num2 = num7 - num8;
  46900. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  46901. };
  46902. return BounceEase;
  46903. }(EasingFunction));
  46904. BABYLON.BounceEase = BounceEase;
  46905. var CubicEase = /** @class */ (function (_super) {
  46906. __extends(CubicEase, _super);
  46907. function CubicEase() {
  46908. return _super !== null && _super.apply(this, arguments) || this;
  46909. }
  46910. CubicEase.prototype.easeInCore = function (gradient) {
  46911. return (gradient * gradient * gradient);
  46912. };
  46913. return CubicEase;
  46914. }(EasingFunction));
  46915. BABYLON.CubicEase = CubicEase;
  46916. var ElasticEase = /** @class */ (function (_super) {
  46917. __extends(ElasticEase, _super);
  46918. function ElasticEase(oscillations, springiness) {
  46919. if (oscillations === void 0) { oscillations = 3; }
  46920. if (springiness === void 0) { springiness = 3; }
  46921. var _this = _super.call(this) || this;
  46922. _this.oscillations = oscillations;
  46923. _this.springiness = springiness;
  46924. return _this;
  46925. }
  46926. ElasticEase.prototype.easeInCore = function (gradient) {
  46927. var num2;
  46928. var num3 = Math.max(0.0, this.oscillations);
  46929. var num = Math.max(0.0, this.springiness);
  46930. if (num == 0) {
  46931. num2 = gradient;
  46932. }
  46933. else {
  46934. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  46935. }
  46936. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  46937. };
  46938. return ElasticEase;
  46939. }(EasingFunction));
  46940. BABYLON.ElasticEase = ElasticEase;
  46941. var ExponentialEase = /** @class */ (function (_super) {
  46942. __extends(ExponentialEase, _super);
  46943. function ExponentialEase(exponent) {
  46944. if (exponent === void 0) { exponent = 2; }
  46945. var _this = _super.call(this) || this;
  46946. _this.exponent = exponent;
  46947. return _this;
  46948. }
  46949. ExponentialEase.prototype.easeInCore = function (gradient) {
  46950. if (this.exponent <= 0) {
  46951. return gradient;
  46952. }
  46953. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  46954. };
  46955. return ExponentialEase;
  46956. }(EasingFunction));
  46957. BABYLON.ExponentialEase = ExponentialEase;
  46958. var PowerEase = /** @class */ (function (_super) {
  46959. __extends(PowerEase, _super);
  46960. function PowerEase(power) {
  46961. if (power === void 0) { power = 2; }
  46962. var _this = _super.call(this) || this;
  46963. _this.power = power;
  46964. return _this;
  46965. }
  46966. PowerEase.prototype.easeInCore = function (gradient) {
  46967. var y = Math.max(0.0, this.power);
  46968. return Math.pow(gradient, y);
  46969. };
  46970. return PowerEase;
  46971. }(EasingFunction));
  46972. BABYLON.PowerEase = PowerEase;
  46973. var QuadraticEase = /** @class */ (function (_super) {
  46974. __extends(QuadraticEase, _super);
  46975. function QuadraticEase() {
  46976. return _super !== null && _super.apply(this, arguments) || this;
  46977. }
  46978. QuadraticEase.prototype.easeInCore = function (gradient) {
  46979. return (gradient * gradient);
  46980. };
  46981. return QuadraticEase;
  46982. }(EasingFunction));
  46983. BABYLON.QuadraticEase = QuadraticEase;
  46984. var QuarticEase = /** @class */ (function (_super) {
  46985. __extends(QuarticEase, _super);
  46986. function QuarticEase() {
  46987. return _super !== null && _super.apply(this, arguments) || this;
  46988. }
  46989. QuarticEase.prototype.easeInCore = function (gradient) {
  46990. return (gradient * gradient * gradient * gradient);
  46991. };
  46992. return QuarticEase;
  46993. }(EasingFunction));
  46994. BABYLON.QuarticEase = QuarticEase;
  46995. var QuinticEase = /** @class */ (function (_super) {
  46996. __extends(QuinticEase, _super);
  46997. function QuinticEase() {
  46998. return _super !== null && _super.apply(this, arguments) || this;
  46999. }
  47000. QuinticEase.prototype.easeInCore = function (gradient) {
  47001. return (gradient * gradient * gradient * gradient * gradient);
  47002. };
  47003. return QuinticEase;
  47004. }(EasingFunction));
  47005. BABYLON.QuinticEase = QuinticEase;
  47006. var SineEase = /** @class */ (function (_super) {
  47007. __extends(SineEase, _super);
  47008. function SineEase() {
  47009. return _super !== null && _super.apply(this, arguments) || this;
  47010. }
  47011. SineEase.prototype.easeInCore = function (gradient) {
  47012. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47013. };
  47014. return SineEase;
  47015. }(EasingFunction));
  47016. BABYLON.SineEase = SineEase;
  47017. var BezierCurveEase = /** @class */ (function (_super) {
  47018. __extends(BezierCurveEase, _super);
  47019. function BezierCurveEase(x1, y1, x2, y2) {
  47020. if (x1 === void 0) { x1 = 0; }
  47021. if (y1 === void 0) { y1 = 0; }
  47022. if (x2 === void 0) { x2 = 1; }
  47023. if (y2 === void 0) { y2 = 1; }
  47024. var _this = _super.call(this) || this;
  47025. _this.x1 = x1;
  47026. _this.y1 = y1;
  47027. _this.x2 = x2;
  47028. _this.y2 = y2;
  47029. return _this;
  47030. }
  47031. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47032. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47033. };
  47034. return BezierCurveEase;
  47035. }(EasingFunction));
  47036. BABYLON.BezierCurveEase = BezierCurveEase;
  47037. })(BABYLON || (BABYLON = {}));
  47038. //# sourceMappingURL=babylon.easing.js.map
  47039. var BABYLON;
  47040. (function (BABYLON) {
  47041. var Condition = /** @class */ (function () {
  47042. function Condition(actionManager) {
  47043. this._actionManager = actionManager;
  47044. }
  47045. Condition.prototype.isValid = function () {
  47046. return true;
  47047. };
  47048. Condition.prototype._getProperty = function (propertyPath) {
  47049. return this._actionManager._getProperty(propertyPath);
  47050. };
  47051. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47052. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47053. };
  47054. Condition.prototype.serialize = function () {
  47055. };
  47056. Condition.prototype._serialize = function (serializedCondition) {
  47057. return {
  47058. type: 2,
  47059. children: [],
  47060. name: serializedCondition.name,
  47061. properties: serializedCondition.properties
  47062. };
  47063. };
  47064. return Condition;
  47065. }());
  47066. BABYLON.Condition = Condition;
  47067. var ValueCondition = /** @class */ (function (_super) {
  47068. __extends(ValueCondition, _super);
  47069. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47070. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47071. var _this = _super.call(this, actionManager) || this;
  47072. _this.propertyPath = propertyPath;
  47073. _this.value = value;
  47074. _this.operator = operator;
  47075. _this._target = target;
  47076. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47077. _this._property = _this._getProperty(_this.propertyPath);
  47078. return _this;
  47079. }
  47080. Object.defineProperty(ValueCondition, "IsEqual", {
  47081. get: function () {
  47082. return ValueCondition._IsEqual;
  47083. },
  47084. enumerable: true,
  47085. configurable: true
  47086. });
  47087. Object.defineProperty(ValueCondition, "IsDifferent", {
  47088. get: function () {
  47089. return ValueCondition._IsDifferent;
  47090. },
  47091. enumerable: true,
  47092. configurable: true
  47093. });
  47094. Object.defineProperty(ValueCondition, "IsGreater", {
  47095. get: function () {
  47096. return ValueCondition._IsGreater;
  47097. },
  47098. enumerable: true,
  47099. configurable: true
  47100. });
  47101. Object.defineProperty(ValueCondition, "IsLesser", {
  47102. get: function () {
  47103. return ValueCondition._IsLesser;
  47104. },
  47105. enumerable: true,
  47106. configurable: true
  47107. });
  47108. // Methods
  47109. ValueCondition.prototype.isValid = function () {
  47110. switch (this.operator) {
  47111. case ValueCondition.IsGreater:
  47112. return this._effectiveTarget[this._property] > this.value;
  47113. case ValueCondition.IsLesser:
  47114. return this._effectiveTarget[this._property] < this.value;
  47115. case ValueCondition.IsEqual:
  47116. case ValueCondition.IsDifferent:
  47117. var check;
  47118. if (this.value.equals) {
  47119. check = this.value.equals(this._effectiveTarget[this._property]);
  47120. }
  47121. else {
  47122. check = this.value === this._effectiveTarget[this._property];
  47123. }
  47124. return this.operator === ValueCondition.IsEqual ? check : !check;
  47125. }
  47126. return false;
  47127. };
  47128. ValueCondition.prototype.serialize = function () {
  47129. return this._serialize({
  47130. name: "ValueCondition",
  47131. properties: [
  47132. BABYLON.Action._GetTargetProperty(this._target),
  47133. { name: "propertyPath", value: this.propertyPath },
  47134. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47135. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47136. ]
  47137. });
  47138. };
  47139. ValueCondition.GetOperatorName = function (operator) {
  47140. switch (operator) {
  47141. case ValueCondition._IsEqual: return "IsEqual";
  47142. case ValueCondition._IsDifferent: return "IsDifferent";
  47143. case ValueCondition._IsGreater: return "IsGreater";
  47144. case ValueCondition._IsLesser: return "IsLesser";
  47145. default: return "";
  47146. }
  47147. };
  47148. // Statics
  47149. ValueCondition._IsEqual = 0;
  47150. ValueCondition._IsDifferent = 1;
  47151. ValueCondition._IsGreater = 2;
  47152. ValueCondition._IsLesser = 3;
  47153. return ValueCondition;
  47154. }(Condition));
  47155. BABYLON.ValueCondition = ValueCondition;
  47156. var PredicateCondition = /** @class */ (function (_super) {
  47157. __extends(PredicateCondition, _super);
  47158. function PredicateCondition(actionManager, predicate) {
  47159. var _this = _super.call(this, actionManager) || this;
  47160. _this.predicate = predicate;
  47161. return _this;
  47162. }
  47163. PredicateCondition.prototype.isValid = function () {
  47164. return this.predicate();
  47165. };
  47166. return PredicateCondition;
  47167. }(Condition));
  47168. BABYLON.PredicateCondition = PredicateCondition;
  47169. var StateCondition = /** @class */ (function (_super) {
  47170. __extends(StateCondition, _super);
  47171. function StateCondition(actionManager, target, value) {
  47172. var _this = _super.call(this, actionManager) || this;
  47173. _this.value = value;
  47174. _this._target = target;
  47175. return _this;
  47176. }
  47177. // Methods
  47178. StateCondition.prototype.isValid = function () {
  47179. return this._target.state === this.value;
  47180. };
  47181. StateCondition.prototype.serialize = function () {
  47182. return this._serialize({
  47183. name: "StateCondition",
  47184. properties: [
  47185. BABYLON.Action._GetTargetProperty(this._target),
  47186. { name: "value", value: this.value }
  47187. ]
  47188. });
  47189. };
  47190. return StateCondition;
  47191. }(Condition));
  47192. BABYLON.StateCondition = StateCondition;
  47193. })(BABYLON || (BABYLON = {}));
  47194. //# sourceMappingURL=babylon.condition.js.map
  47195. var BABYLON;
  47196. (function (BABYLON) {
  47197. var Action = /** @class */ (function () {
  47198. function Action(triggerOptions, condition) {
  47199. this.triggerOptions = triggerOptions;
  47200. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47201. if (triggerOptions.parameter) {
  47202. this.trigger = triggerOptions.trigger;
  47203. this._triggerParameter = triggerOptions.parameter;
  47204. }
  47205. else {
  47206. this.trigger = triggerOptions;
  47207. }
  47208. this._nextActiveAction = this;
  47209. this._condition = condition;
  47210. }
  47211. // Methods
  47212. Action.prototype._prepare = function () {
  47213. };
  47214. Action.prototype.getTriggerParameter = function () {
  47215. return this._triggerParameter;
  47216. };
  47217. Action.prototype._executeCurrent = function (evt) {
  47218. if (this._nextActiveAction._condition) {
  47219. var condition = this._nextActiveAction._condition;
  47220. var currentRenderId = this._actionManager.getScene().getRenderId();
  47221. // We cache the current evaluation for the current frame
  47222. if (condition._evaluationId === currentRenderId) {
  47223. if (!condition._currentResult) {
  47224. return;
  47225. }
  47226. }
  47227. else {
  47228. condition._evaluationId = currentRenderId;
  47229. if (!condition.isValid()) {
  47230. condition._currentResult = false;
  47231. return;
  47232. }
  47233. condition._currentResult = true;
  47234. }
  47235. }
  47236. this.onBeforeExecuteObservable.notifyObservers(this);
  47237. this._nextActiveAction.execute(evt);
  47238. this.skipToNextActiveAction();
  47239. };
  47240. Action.prototype.execute = function (evt) {
  47241. };
  47242. Action.prototype.skipToNextActiveAction = function () {
  47243. if (this._nextActiveAction._child) {
  47244. if (!this._nextActiveAction._child._actionManager) {
  47245. this._nextActiveAction._child._actionManager = this._actionManager;
  47246. }
  47247. this._nextActiveAction = this._nextActiveAction._child;
  47248. }
  47249. else {
  47250. this._nextActiveAction = this;
  47251. }
  47252. };
  47253. Action.prototype.then = function (action) {
  47254. this._child = action;
  47255. action._actionManager = this._actionManager;
  47256. action._prepare();
  47257. return action;
  47258. };
  47259. Action.prototype._getProperty = function (propertyPath) {
  47260. return this._actionManager._getProperty(propertyPath);
  47261. };
  47262. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47263. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47264. };
  47265. Action.prototype.serialize = function (parent) {
  47266. };
  47267. // Called by BABYLON.Action objects in serialize(...). Internal use
  47268. Action.prototype._serialize = function (serializedAction, parent) {
  47269. var serializationObject = {
  47270. type: 1,
  47271. children: [],
  47272. name: serializedAction.name,
  47273. properties: serializedAction.properties || []
  47274. };
  47275. // Serialize child
  47276. if (this._child) {
  47277. this._child.serialize(serializationObject);
  47278. }
  47279. // Check if "this" has a condition
  47280. if (this._condition) {
  47281. var serializedCondition = this._condition.serialize();
  47282. serializedCondition.children.push(serializationObject);
  47283. if (parent) {
  47284. parent.children.push(serializedCondition);
  47285. }
  47286. return serializedCondition;
  47287. }
  47288. if (parent) {
  47289. parent.children.push(serializationObject);
  47290. }
  47291. return serializationObject;
  47292. };
  47293. Action._SerializeValueAsString = function (value) {
  47294. if (typeof value === "number") {
  47295. return value.toString();
  47296. }
  47297. if (typeof value === "boolean") {
  47298. return value ? "true" : "false";
  47299. }
  47300. if (value instanceof BABYLON.Vector2) {
  47301. return value.x + ", " + value.y;
  47302. }
  47303. if (value instanceof BABYLON.Vector3) {
  47304. return value.x + ", " + value.y + ", " + value.z;
  47305. }
  47306. if (value instanceof BABYLON.Color3) {
  47307. return value.r + ", " + value.g + ", " + value.b;
  47308. }
  47309. if (value instanceof BABYLON.Color4) {
  47310. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47311. }
  47312. return value; // string
  47313. };
  47314. Action._GetTargetProperty = function (target) {
  47315. return {
  47316. name: "target",
  47317. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47318. : target instanceof BABYLON.Light ? "LightProperties"
  47319. : target instanceof BABYLON.Camera ? "CameraProperties"
  47320. : "SceneProperties",
  47321. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47322. };
  47323. };
  47324. return Action;
  47325. }());
  47326. BABYLON.Action = Action;
  47327. })(BABYLON || (BABYLON = {}));
  47328. //# sourceMappingURL=babylon.action.js.map
  47329. var BABYLON;
  47330. (function (BABYLON) {
  47331. /**
  47332. * ActionEvent is the event beint sent when an action is triggered.
  47333. */
  47334. var ActionEvent = /** @class */ (function () {
  47335. /**
  47336. * @param source The mesh or sprite that triggered the action.
  47337. * @param pointerX The X mouse cursor position at the time of the event
  47338. * @param pointerY The Y mouse cursor position at the time of the event
  47339. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47340. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47341. */
  47342. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47343. this.source = source;
  47344. this.pointerX = pointerX;
  47345. this.pointerY = pointerY;
  47346. this.meshUnderPointer = meshUnderPointer;
  47347. this.sourceEvent = sourceEvent;
  47348. this.additionalData = additionalData;
  47349. }
  47350. /**
  47351. * Helper function to auto-create an ActionEvent from a source mesh.
  47352. * @param source The source mesh that triggered the event
  47353. * @param evt {Event} The original (browser) event
  47354. */
  47355. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47356. var scene = source.getScene();
  47357. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47358. };
  47359. /**
  47360. * Helper function to auto-create an ActionEvent from a source mesh.
  47361. * @param source The source sprite that triggered the event
  47362. * @param scene Scene associated with the sprite
  47363. * @param evt {Event} The original (browser) event
  47364. */
  47365. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47366. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47367. };
  47368. /**
  47369. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47370. * @param scene the scene where the event occurred
  47371. * @param evt {Event} The original (browser) event
  47372. */
  47373. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47374. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47375. };
  47376. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47377. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47378. };
  47379. return ActionEvent;
  47380. }());
  47381. BABYLON.ActionEvent = ActionEvent;
  47382. /**
  47383. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47384. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47385. */
  47386. var ActionManager = /** @class */ (function () {
  47387. function ActionManager(scene) {
  47388. // Members
  47389. this.actions = new Array();
  47390. this.hoverCursor = '';
  47391. this._scene = scene;
  47392. scene._actionManagers.push(this);
  47393. }
  47394. Object.defineProperty(ActionManager, "NothingTrigger", {
  47395. get: function () {
  47396. return ActionManager._NothingTrigger;
  47397. },
  47398. enumerable: true,
  47399. configurable: true
  47400. });
  47401. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47402. get: function () {
  47403. return ActionManager._OnPickTrigger;
  47404. },
  47405. enumerable: true,
  47406. configurable: true
  47407. });
  47408. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47409. get: function () {
  47410. return ActionManager._OnLeftPickTrigger;
  47411. },
  47412. enumerable: true,
  47413. configurable: true
  47414. });
  47415. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47416. get: function () {
  47417. return ActionManager._OnRightPickTrigger;
  47418. },
  47419. enumerable: true,
  47420. configurable: true
  47421. });
  47422. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47423. get: function () {
  47424. return ActionManager._OnCenterPickTrigger;
  47425. },
  47426. enumerable: true,
  47427. configurable: true
  47428. });
  47429. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47430. get: function () {
  47431. return ActionManager._OnPickDownTrigger;
  47432. },
  47433. enumerable: true,
  47434. configurable: true
  47435. });
  47436. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47437. get: function () {
  47438. return ActionManager._OnDoublePickTrigger;
  47439. },
  47440. enumerable: true,
  47441. configurable: true
  47442. });
  47443. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47444. get: function () {
  47445. return ActionManager._OnPickUpTrigger;
  47446. },
  47447. enumerable: true,
  47448. configurable: true
  47449. });
  47450. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47451. /// This trigger will only be raised if you also declared a OnPickDown
  47452. get: function () {
  47453. return ActionManager._OnPickOutTrigger;
  47454. },
  47455. enumerable: true,
  47456. configurable: true
  47457. });
  47458. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47459. get: function () {
  47460. return ActionManager._OnLongPressTrigger;
  47461. },
  47462. enumerable: true,
  47463. configurable: true
  47464. });
  47465. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47466. get: function () {
  47467. return ActionManager._OnPointerOverTrigger;
  47468. },
  47469. enumerable: true,
  47470. configurable: true
  47471. });
  47472. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47473. get: function () {
  47474. return ActionManager._OnPointerOutTrigger;
  47475. },
  47476. enumerable: true,
  47477. configurable: true
  47478. });
  47479. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47480. get: function () {
  47481. return ActionManager._OnEveryFrameTrigger;
  47482. },
  47483. enumerable: true,
  47484. configurable: true
  47485. });
  47486. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47487. get: function () {
  47488. return ActionManager._OnIntersectionEnterTrigger;
  47489. },
  47490. enumerable: true,
  47491. configurable: true
  47492. });
  47493. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47494. get: function () {
  47495. return ActionManager._OnIntersectionExitTrigger;
  47496. },
  47497. enumerable: true,
  47498. configurable: true
  47499. });
  47500. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47501. get: function () {
  47502. return ActionManager._OnKeyDownTrigger;
  47503. },
  47504. enumerable: true,
  47505. configurable: true
  47506. });
  47507. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47508. get: function () {
  47509. return ActionManager._OnKeyUpTrigger;
  47510. },
  47511. enumerable: true,
  47512. configurable: true
  47513. });
  47514. // Methods
  47515. ActionManager.prototype.dispose = function () {
  47516. var index = this._scene._actionManagers.indexOf(this);
  47517. for (var i = 0; i < this.actions.length; i++) {
  47518. var action = this.actions[i];
  47519. ActionManager.Triggers[action.trigger]--;
  47520. if (ActionManager.Triggers[action.trigger] === 0) {
  47521. delete ActionManager.Triggers[action.trigger];
  47522. }
  47523. }
  47524. if (index > -1) {
  47525. this._scene._actionManagers.splice(index, 1);
  47526. }
  47527. };
  47528. ActionManager.prototype.getScene = function () {
  47529. return this._scene;
  47530. };
  47531. /**
  47532. * Does this action manager handles actions of any of the given triggers
  47533. * @param {number[]} triggers - the triggers to be tested
  47534. * @return {boolean} whether one (or more) of the triggers is handeled
  47535. */
  47536. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47537. for (var index = 0; index < this.actions.length; index++) {
  47538. var action = this.actions[index];
  47539. if (triggers.indexOf(action.trigger) > -1) {
  47540. return true;
  47541. }
  47542. }
  47543. return false;
  47544. };
  47545. /**
  47546. * Does this action manager handles actions of a given trigger
  47547. * @param {number} trigger - the trigger to be tested
  47548. * @return {boolean} whether the trigger is handeled
  47549. */
  47550. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47551. for (var index = 0; index < this.actions.length; index++) {
  47552. var action = this.actions[index];
  47553. if (action.trigger === trigger) {
  47554. return true;
  47555. }
  47556. }
  47557. return false;
  47558. };
  47559. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47560. /**
  47561. * Does this action manager has pointer triggers
  47562. * @return {boolean} whether or not it has pointer triggers
  47563. */
  47564. get: function () {
  47565. for (var index = 0; index < this.actions.length; index++) {
  47566. var action = this.actions[index];
  47567. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47568. return true;
  47569. }
  47570. }
  47571. return false;
  47572. },
  47573. enumerable: true,
  47574. configurable: true
  47575. });
  47576. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47577. /**
  47578. * Does this action manager has pick triggers
  47579. * @return {boolean} whether or not it has pick triggers
  47580. */
  47581. get: function () {
  47582. for (var index = 0; index < this.actions.length; index++) {
  47583. var action = this.actions[index];
  47584. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47585. return true;
  47586. }
  47587. }
  47588. return false;
  47589. },
  47590. enumerable: true,
  47591. configurable: true
  47592. });
  47593. Object.defineProperty(ActionManager, "HasTriggers", {
  47594. /**
  47595. * Does exist one action manager with at least one trigger
  47596. * @return {boolean} whether or not it exists one action manager with one trigger
  47597. **/
  47598. get: function () {
  47599. for (var t in ActionManager.Triggers) {
  47600. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47601. return true;
  47602. }
  47603. }
  47604. return false;
  47605. },
  47606. enumerable: true,
  47607. configurable: true
  47608. });
  47609. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47610. /**
  47611. * Does exist one action manager with at least one pick trigger
  47612. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47613. **/
  47614. get: function () {
  47615. for (var t in ActionManager.Triggers) {
  47616. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47617. var t_int = parseInt(t);
  47618. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  47619. return true;
  47620. }
  47621. }
  47622. }
  47623. return false;
  47624. },
  47625. enumerable: true,
  47626. configurable: true
  47627. });
  47628. /**
  47629. * Does exist one action manager that handles actions of a given trigger
  47630. * @param {number} trigger - the trigger to be tested
  47631. * @return {boolean} whether the trigger is handeled by at least one action manager
  47632. **/
  47633. ActionManager.HasSpecificTrigger = function (trigger) {
  47634. for (var t in ActionManager.Triggers) {
  47635. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47636. var t_int = parseInt(t);
  47637. if (t_int === trigger) {
  47638. return true;
  47639. }
  47640. }
  47641. }
  47642. return false;
  47643. };
  47644. /**
  47645. * Registers an action to this action manager
  47646. * @param {BABYLON.Action} action - the action to be registered
  47647. * @return {BABYLON.Action} the action amended (prepared) after registration
  47648. */
  47649. ActionManager.prototype.registerAction = function (action) {
  47650. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  47651. if (this.getScene().actionManager !== this) {
  47652. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  47653. return null;
  47654. }
  47655. }
  47656. this.actions.push(action);
  47657. if (ActionManager.Triggers[action.trigger]) {
  47658. ActionManager.Triggers[action.trigger]++;
  47659. }
  47660. else {
  47661. ActionManager.Triggers[action.trigger] = 1;
  47662. }
  47663. action._actionManager = this;
  47664. action._prepare();
  47665. return action;
  47666. };
  47667. /**
  47668. * Unregisters an action to this action manager
  47669. * @param action The action to be unregistered
  47670. * @return whether the action has been unregistered
  47671. */
  47672. ActionManager.prototype.unregisterAction = function (action) {
  47673. var index = this.actions.indexOf(action);
  47674. if (index !== -1) {
  47675. this.actions.splice(index, 1);
  47676. ActionManager.Triggers[action.trigger] -= 1;
  47677. if (ActionManager.Triggers[action.trigger] === 0) {
  47678. delete ActionManager.Triggers[action.trigger];
  47679. }
  47680. delete action._actionManager;
  47681. return true;
  47682. }
  47683. return false;
  47684. };
  47685. /**
  47686. * Process a specific trigger
  47687. * @param {number} trigger - the trigger to process
  47688. * @param evt {BABYLON.ActionEvent} the event details to be processed
  47689. */
  47690. ActionManager.prototype.processTrigger = function (trigger, evt) {
  47691. for (var index = 0; index < this.actions.length; index++) {
  47692. var action = this.actions[index];
  47693. if (action.trigger === trigger) {
  47694. if (evt) {
  47695. if (trigger === ActionManager.OnKeyUpTrigger
  47696. || trigger === ActionManager.OnKeyDownTrigger) {
  47697. var parameter = action.getTriggerParameter();
  47698. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  47699. if (!parameter.toLowerCase) {
  47700. continue;
  47701. }
  47702. var lowerCase = parameter.toLowerCase();
  47703. if (lowerCase !== evt.sourceEvent.key) {
  47704. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  47705. var actualkey = String.fromCharCode(unicode).toLowerCase();
  47706. if (actualkey !== lowerCase) {
  47707. continue;
  47708. }
  47709. }
  47710. }
  47711. }
  47712. }
  47713. action._executeCurrent(evt);
  47714. }
  47715. }
  47716. };
  47717. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  47718. var properties = propertyPath.split(".");
  47719. for (var index = 0; index < properties.length - 1; index++) {
  47720. target = target[properties[index]];
  47721. }
  47722. return target;
  47723. };
  47724. ActionManager.prototype._getProperty = function (propertyPath) {
  47725. var properties = propertyPath.split(".");
  47726. return properties[properties.length - 1];
  47727. };
  47728. ActionManager.prototype.serialize = function (name) {
  47729. var root = {
  47730. children: new Array(),
  47731. name: name,
  47732. type: 3,
  47733. properties: new Array() // Empty for root but required
  47734. };
  47735. for (var i = 0; i < this.actions.length; i++) {
  47736. var triggerObject = {
  47737. type: 0,
  47738. children: new Array(),
  47739. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  47740. properties: new Array()
  47741. };
  47742. var triggerOptions = this.actions[i].triggerOptions;
  47743. if (triggerOptions && typeof triggerOptions !== "number") {
  47744. if (triggerOptions.parameter instanceof BABYLON.Node) {
  47745. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  47746. }
  47747. else {
  47748. var parameter = {};
  47749. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  47750. if (triggerOptions.parameter.mesh) {
  47751. parameter._meshId = triggerOptions.parameter.mesh.id;
  47752. }
  47753. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  47754. }
  47755. }
  47756. // Serialize child action, recursively
  47757. this.actions[i].serialize(triggerObject);
  47758. // Add serialized trigger
  47759. root.children.push(triggerObject);
  47760. }
  47761. return root;
  47762. };
  47763. ActionManager.Parse = function (parsedActions, object, scene) {
  47764. var actionManager = new ActionManager(scene);
  47765. if (object === null)
  47766. scene.actionManager = actionManager;
  47767. else
  47768. object.actionManager = actionManager;
  47769. // instanciate a new object
  47770. var instanciate = function (name, params) {
  47771. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  47772. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  47773. newInstance.constructor.apply(newInstance, params);
  47774. return newInstance;
  47775. };
  47776. var parseParameter = function (name, value, target, propertyPath) {
  47777. if (propertyPath === null) {
  47778. // String, boolean or float
  47779. var floatValue = parseFloat(value);
  47780. if (value === "true" || value === "false")
  47781. return value === "true";
  47782. else
  47783. return isNaN(floatValue) ? value : floatValue;
  47784. }
  47785. var effectiveTarget = propertyPath.split(".");
  47786. var values = value.split(",");
  47787. // Get effective Target
  47788. for (var i = 0; i < effectiveTarget.length; i++) {
  47789. target = target[effectiveTarget[i]];
  47790. }
  47791. // Return appropriate value with its type
  47792. if (typeof (target) === "boolean")
  47793. return values[0] === "true";
  47794. if (typeof (target) === "string")
  47795. return values[0];
  47796. // Parameters with multiple values such as Vector3 etc.
  47797. var split = new Array();
  47798. for (var i = 0; i < values.length; i++)
  47799. split.push(parseFloat(values[i]));
  47800. if (target instanceof BABYLON.Vector3)
  47801. return BABYLON.Vector3.FromArray(split);
  47802. if (target instanceof BABYLON.Vector4)
  47803. return BABYLON.Vector4.FromArray(split);
  47804. if (target instanceof BABYLON.Color3)
  47805. return BABYLON.Color3.FromArray(split);
  47806. if (target instanceof BABYLON.Color4)
  47807. return BABYLON.Color4.FromArray(split);
  47808. return parseFloat(values[0]);
  47809. };
  47810. // traverse graph per trigger
  47811. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  47812. if (combineArray === void 0) { combineArray = null; }
  47813. if (parsedAction.detached)
  47814. return;
  47815. var parameters = new Array();
  47816. var target = null;
  47817. var propertyPath = null;
  47818. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  47819. // Parameters
  47820. if (parsedAction.type === 2)
  47821. parameters.push(actionManager);
  47822. else
  47823. parameters.push(trigger);
  47824. if (combine) {
  47825. var actions = new Array();
  47826. for (var j = 0; j < parsedAction.combine.length; j++) {
  47827. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  47828. }
  47829. parameters.push(actions);
  47830. }
  47831. else {
  47832. for (var i = 0; i < parsedAction.properties.length; i++) {
  47833. var value = parsedAction.properties[i].value;
  47834. var name = parsedAction.properties[i].name;
  47835. var targetType = parsedAction.properties[i].targetType;
  47836. if (name === "target")
  47837. if (targetType !== null && targetType === "SceneProperties")
  47838. value = target = scene;
  47839. else
  47840. value = target = scene.getNodeByName(value);
  47841. else if (name === "parent")
  47842. value = scene.getNodeByName(value);
  47843. else if (name === "sound")
  47844. value = scene.getSoundByName(value);
  47845. else if (name !== "propertyPath") {
  47846. if (parsedAction.type === 2 && name === "operator")
  47847. value = BABYLON.ValueCondition[value];
  47848. else
  47849. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  47850. }
  47851. else {
  47852. propertyPath = value;
  47853. }
  47854. parameters.push(value);
  47855. }
  47856. }
  47857. if (combineArray === null) {
  47858. parameters.push(condition);
  47859. }
  47860. else {
  47861. parameters.push(null);
  47862. }
  47863. // If interpolate value action
  47864. if (parsedAction.name === "InterpolateValueAction") {
  47865. var param = parameters[parameters.length - 2];
  47866. parameters[parameters.length - 1] = param;
  47867. parameters[parameters.length - 2] = condition;
  47868. }
  47869. // Action or condition(s) and not CombineAction
  47870. var newAction = instanciate(parsedAction.name, parameters);
  47871. if (newAction instanceof BABYLON.Condition && condition !== null) {
  47872. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  47873. if (action)
  47874. action.then(nothing);
  47875. else
  47876. actionManager.registerAction(nothing);
  47877. action = nothing;
  47878. }
  47879. if (combineArray === null) {
  47880. if (newAction instanceof BABYLON.Condition) {
  47881. condition = newAction;
  47882. newAction = action;
  47883. }
  47884. else {
  47885. condition = null;
  47886. if (action)
  47887. action.then(newAction);
  47888. else
  47889. actionManager.registerAction(newAction);
  47890. }
  47891. }
  47892. else {
  47893. combineArray.push(newAction);
  47894. }
  47895. for (var i = 0; i < parsedAction.children.length; i++)
  47896. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  47897. };
  47898. // triggers
  47899. for (var i = 0; i < parsedActions.children.length; i++) {
  47900. var triggerParams;
  47901. var trigger = parsedActions.children[i];
  47902. if (trigger.properties.length > 0) {
  47903. var param = trigger.properties[0].value;
  47904. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  47905. if (value._meshId) {
  47906. value.mesh = scene.getMeshByID(value._meshId);
  47907. }
  47908. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  47909. }
  47910. else
  47911. triggerParams = ActionManager[trigger.name];
  47912. for (var j = 0; j < trigger.children.length; j++) {
  47913. if (!trigger.detached)
  47914. traverse(trigger.children[j], triggerParams, null, null);
  47915. }
  47916. }
  47917. };
  47918. ActionManager.GetTriggerName = function (trigger) {
  47919. switch (trigger) {
  47920. case 0: return "NothingTrigger";
  47921. case 1: return "OnPickTrigger";
  47922. case 2: return "OnLeftPickTrigger";
  47923. case 3: return "OnRightPickTrigger";
  47924. case 4: return "OnCenterPickTrigger";
  47925. case 5: return "OnPickDownTrigger";
  47926. case 6: return "OnPickUpTrigger";
  47927. case 7: return "OnLongPressTrigger";
  47928. case 8: return "OnPointerOverTrigger";
  47929. case 9: return "OnPointerOutTrigger";
  47930. case 10: return "OnEveryFrameTrigger";
  47931. case 11: return "OnIntersectionEnterTrigger";
  47932. case 12: return "OnIntersectionExitTrigger";
  47933. case 13: return "OnKeyDownTrigger";
  47934. case 14: return "OnKeyUpTrigger";
  47935. case 15: return "OnPickOutTrigger";
  47936. default: return "";
  47937. }
  47938. };
  47939. // Statics
  47940. ActionManager._NothingTrigger = 0;
  47941. ActionManager._OnPickTrigger = 1;
  47942. ActionManager._OnLeftPickTrigger = 2;
  47943. ActionManager._OnRightPickTrigger = 3;
  47944. ActionManager._OnCenterPickTrigger = 4;
  47945. ActionManager._OnPickDownTrigger = 5;
  47946. ActionManager._OnDoublePickTrigger = 6;
  47947. ActionManager._OnPickUpTrigger = 7;
  47948. ActionManager._OnLongPressTrigger = 8;
  47949. ActionManager._OnPointerOverTrigger = 9;
  47950. ActionManager._OnPointerOutTrigger = 10;
  47951. ActionManager._OnEveryFrameTrigger = 11;
  47952. ActionManager._OnIntersectionEnterTrigger = 12;
  47953. ActionManager._OnIntersectionExitTrigger = 13;
  47954. ActionManager._OnKeyDownTrigger = 14;
  47955. ActionManager._OnKeyUpTrigger = 15;
  47956. ActionManager._OnPickOutTrigger = 16;
  47957. ActionManager.Triggers = {};
  47958. return ActionManager;
  47959. }());
  47960. BABYLON.ActionManager = ActionManager;
  47961. })(BABYLON || (BABYLON = {}));
  47962. //# sourceMappingURL=babylon.actionManager.js.map
  47963. var BABYLON;
  47964. (function (BABYLON) {
  47965. var InterpolateValueAction = /** @class */ (function (_super) {
  47966. __extends(InterpolateValueAction, _super);
  47967. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  47968. if (duration === void 0) { duration = 1000; }
  47969. var _this = _super.call(this, triggerOptions, condition) || this;
  47970. _this.propertyPath = propertyPath;
  47971. _this.value = value;
  47972. _this.duration = duration;
  47973. _this.stopOtherAnimations = stopOtherAnimations;
  47974. _this.onInterpolationDone = onInterpolationDone;
  47975. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  47976. _this._target = _this._effectiveTarget = target;
  47977. return _this;
  47978. }
  47979. InterpolateValueAction.prototype._prepare = function () {
  47980. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47981. this._property = this._getProperty(this.propertyPath);
  47982. };
  47983. InterpolateValueAction.prototype.execute = function () {
  47984. var _this = this;
  47985. var scene = this._actionManager.getScene();
  47986. var keys = [
  47987. {
  47988. frame: 0,
  47989. value: this._effectiveTarget[this._property]
  47990. }, {
  47991. frame: 100,
  47992. value: this.value
  47993. }
  47994. ];
  47995. var dataType;
  47996. if (typeof this.value === "number") {
  47997. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  47998. }
  47999. else if (this.value instanceof BABYLON.Color3) {
  48000. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48001. }
  48002. else if (this.value instanceof BABYLON.Vector3) {
  48003. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48004. }
  48005. else if (this.value instanceof BABYLON.Matrix) {
  48006. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48007. }
  48008. else if (this.value instanceof BABYLON.Quaternion) {
  48009. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48010. }
  48011. else {
  48012. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48013. return;
  48014. }
  48015. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48016. animation.setKeys(keys);
  48017. if (this.stopOtherAnimations) {
  48018. scene.stopAnimation(this._effectiveTarget);
  48019. }
  48020. var wrapper = function () {
  48021. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48022. if (_this.onInterpolationDone) {
  48023. _this.onInterpolationDone();
  48024. }
  48025. };
  48026. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48027. };
  48028. InterpolateValueAction.prototype.serialize = function (parent) {
  48029. return _super.prototype._serialize.call(this, {
  48030. name: "InterpolateValueAction",
  48031. properties: [
  48032. BABYLON.Action._GetTargetProperty(this._target),
  48033. { name: "propertyPath", value: this.propertyPath },
  48034. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48035. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48036. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48037. ]
  48038. }, parent);
  48039. };
  48040. return InterpolateValueAction;
  48041. }(BABYLON.Action));
  48042. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48043. })(BABYLON || (BABYLON = {}));
  48044. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48045. var BABYLON;
  48046. (function (BABYLON) {
  48047. var SwitchBooleanAction = /** @class */ (function (_super) {
  48048. __extends(SwitchBooleanAction, _super);
  48049. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48050. var _this = _super.call(this, triggerOptions, condition) || this;
  48051. _this.propertyPath = propertyPath;
  48052. _this._target = _this._effectiveTarget = target;
  48053. return _this;
  48054. }
  48055. SwitchBooleanAction.prototype._prepare = function () {
  48056. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48057. this._property = this._getProperty(this.propertyPath);
  48058. };
  48059. SwitchBooleanAction.prototype.execute = function () {
  48060. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48061. };
  48062. SwitchBooleanAction.prototype.serialize = function (parent) {
  48063. return _super.prototype._serialize.call(this, {
  48064. name: "SwitchBooleanAction",
  48065. properties: [
  48066. BABYLON.Action._GetTargetProperty(this._target),
  48067. { name: "propertyPath", value: this.propertyPath }
  48068. ]
  48069. }, parent);
  48070. };
  48071. return SwitchBooleanAction;
  48072. }(BABYLON.Action));
  48073. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48074. var SetStateAction = /** @class */ (function (_super) {
  48075. __extends(SetStateAction, _super);
  48076. function SetStateAction(triggerOptions, target, value, condition) {
  48077. var _this = _super.call(this, triggerOptions, condition) || this;
  48078. _this.value = value;
  48079. _this._target = target;
  48080. return _this;
  48081. }
  48082. SetStateAction.prototype.execute = function () {
  48083. this._target.state = this.value;
  48084. };
  48085. SetStateAction.prototype.serialize = function (parent) {
  48086. return _super.prototype._serialize.call(this, {
  48087. name: "SetStateAction",
  48088. properties: [
  48089. BABYLON.Action._GetTargetProperty(this._target),
  48090. { name: "value", value: this.value }
  48091. ]
  48092. }, parent);
  48093. };
  48094. return SetStateAction;
  48095. }(BABYLON.Action));
  48096. BABYLON.SetStateAction = SetStateAction;
  48097. var SetValueAction = /** @class */ (function (_super) {
  48098. __extends(SetValueAction, _super);
  48099. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48100. var _this = _super.call(this, triggerOptions, condition) || this;
  48101. _this.propertyPath = propertyPath;
  48102. _this.value = value;
  48103. _this._target = _this._effectiveTarget = target;
  48104. return _this;
  48105. }
  48106. SetValueAction.prototype._prepare = function () {
  48107. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48108. this._property = this._getProperty(this.propertyPath);
  48109. };
  48110. SetValueAction.prototype.execute = function () {
  48111. this._effectiveTarget[this._property] = this.value;
  48112. if (this._target.markAsDirty) {
  48113. this._target.markAsDirty(this._property);
  48114. }
  48115. };
  48116. SetValueAction.prototype.serialize = function (parent) {
  48117. return _super.prototype._serialize.call(this, {
  48118. name: "SetValueAction",
  48119. properties: [
  48120. BABYLON.Action._GetTargetProperty(this._target),
  48121. { name: "propertyPath", value: this.propertyPath },
  48122. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48123. ]
  48124. }, parent);
  48125. };
  48126. return SetValueAction;
  48127. }(BABYLON.Action));
  48128. BABYLON.SetValueAction = SetValueAction;
  48129. var IncrementValueAction = /** @class */ (function (_super) {
  48130. __extends(IncrementValueAction, _super);
  48131. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48132. var _this = _super.call(this, triggerOptions, condition) || this;
  48133. _this.propertyPath = propertyPath;
  48134. _this.value = value;
  48135. _this._target = _this._effectiveTarget = target;
  48136. return _this;
  48137. }
  48138. IncrementValueAction.prototype._prepare = function () {
  48139. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48140. this._property = this._getProperty(this.propertyPath);
  48141. if (typeof this._effectiveTarget[this._property] !== "number") {
  48142. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48143. }
  48144. };
  48145. IncrementValueAction.prototype.execute = function () {
  48146. this._effectiveTarget[this._property] += this.value;
  48147. if (this._target.markAsDirty) {
  48148. this._target.markAsDirty(this._property);
  48149. }
  48150. };
  48151. IncrementValueAction.prototype.serialize = function (parent) {
  48152. return _super.prototype._serialize.call(this, {
  48153. name: "IncrementValueAction",
  48154. properties: [
  48155. BABYLON.Action._GetTargetProperty(this._target),
  48156. { name: "propertyPath", value: this.propertyPath },
  48157. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48158. ]
  48159. }, parent);
  48160. };
  48161. return IncrementValueAction;
  48162. }(BABYLON.Action));
  48163. BABYLON.IncrementValueAction = IncrementValueAction;
  48164. var PlayAnimationAction = /** @class */ (function (_super) {
  48165. __extends(PlayAnimationAction, _super);
  48166. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48167. var _this = _super.call(this, triggerOptions, condition) || this;
  48168. _this.from = from;
  48169. _this.to = to;
  48170. _this.loop = loop;
  48171. _this._target = target;
  48172. return _this;
  48173. }
  48174. PlayAnimationAction.prototype._prepare = function () {
  48175. };
  48176. PlayAnimationAction.prototype.execute = function () {
  48177. var scene = this._actionManager.getScene();
  48178. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48179. };
  48180. PlayAnimationAction.prototype.serialize = function (parent) {
  48181. return _super.prototype._serialize.call(this, {
  48182. name: "PlayAnimationAction",
  48183. properties: [
  48184. BABYLON.Action._GetTargetProperty(this._target),
  48185. { name: "from", value: String(this.from) },
  48186. { name: "to", value: String(this.to) },
  48187. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48188. ]
  48189. }, parent);
  48190. };
  48191. return PlayAnimationAction;
  48192. }(BABYLON.Action));
  48193. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48194. var StopAnimationAction = /** @class */ (function (_super) {
  48195. __extends(StopAnimationAction, _super);
  48196. function StopAnimationAction(triggerOptions, target, condition) {
  48197. var _this = _super.call(this, triggerOptions, condition) || this;
  48198. _this._target = target;
  48199. return _this;
  48200. }
  48201. StopAnimationAction.prototype._prepare = function () {
  48202. };
  48203. StopAnimationAction.prototype.execute = function () {
  48204. var scene = this._actionManager.getScene();
  48205. scene.stopAnimation(this._target);
  48206. };
  48207. StopAnimationAction.prototype.serialize = function (parent) {
  48208. return _super.prototype._serialize.call(this, {
  48209. name: "StopAnimationAction",
  48210. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48211. }, parent);
  48212. };
  48213. return StopAnimationAction;
  48214. }(BABYLON.Action));
  48215. BABYLON.StopAnimationAction = StopAnimationAction;
  48216. var DoNothingAction = /** @class */ (function (_super) {
  48217. __extends(DoNothingAction, _super);
  48218. function DoNothingAction(triggerOptions, condition) {
  48219. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48220. return _super.call(this, triggerOptions, condition) || this;
  48221. }
  48222. DoNothingAction.prototype.execute = function () {
  48223. };
  48224. DoNothingAction.prototype.serialize = function (parent) {
  48225. return _super.prototype._serialize.call(this, {
  48226. name: "DoNothingAction",
  48227. properties: []
  48228. }, parent);
  48229. };
  48230. return DoNothingAction;
  48231. }(BABYLON.Action));
  48232. BABYLON.DoNothingAction = DoNothingAction;
  48233. var CombineAction = /** @class */ (function (_super) {
  48234. __extends(CombineAction, _super);
  48235. function CombineAction(triggerOptions, children, condition) {
  48236. var _this = _super.call(this, triggerOptions, condition) || this;
  48237. _this.children = children;
  48238. return _this;
  48239. }
  48240. CombineAction.prototype._prepare = function () {
  48241. for (var index = 0; index < this.children.length; index++) {
  48242. this.children[index]._actionManager = this._actionManager;
  48243. this.children[index]._prepare();
  48244. }
  48245. };
  48246. CombineAction.prototype.execute = function (evt) {
  48247. for (var index = 0; index < this.children.length; index++) {
  48248. this.children[index].execute(evt);
  48249. }
  48250. };
  48251. CombineAction.prototype.serialize = function (parent) {
  48252. var serializationObject = _super.prototype._serialize.call(this, {
  48253. name: "CombineAction",
  48254. properties: [],
  48255. combine: []
  48256. }, parent);
  48257. for (var i = 0; i < this.children.length; i++) {
  48258. serializationObject.combine.push(this.children[i].serialize(null));
  48259. }
  48260. return serializationObject;
  48261. };
  48262. return CombineAction;
  48263. }(BABYLON.Action));
  48264. BABYLON.CombineAction = CombineAction;
  48265. var ExecuteCodeAction = /** @class */ (function (_super) {
  48266. __extends(ExecuteCodeAction, _super);
  48267. function ExecuteCodeAction(triggerOptions, func, condition) {
  48268. var _this = _super.call(this, triggerOptions, condition) || this;
  48269. _this.func = func;
  48270. return _this;
  48271. }
  48272. ExecuteCodeAction.prototype.execute = function (evt) {
  48273. this.func(evt);
  48274. };
  48275. return ExecuteCodeAction;
  48276. }(BABYLON.Action));
  48277. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48278. var SetParentAction = /** @class */ (function (_super) {
  48279. __extends(SetParentAction, _super);
  48280. function SetParentAction(triggerOptions, target, parent, condition) {
  48281. var _this = _super.call(this, triggerOptions, condition) || this;
  48282. _this._target = target;
  48283. _this._parent = parent;
  48284. return _this;
  48285. }
  48286. SetParentAction.prototype._prepare = function () {
  48287. };
  48288. SetParentAction.prototype.execute = function () {
  48289. if (this._target.parent === this._parent) {
  48290. return;
  48291. }
  48292. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48293. invertParentWorldMatrix.invert();
  48294. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48295. this._target.parent = this._parent;
  48296. };
  48297. SetParentAction.prototype.serialize = function (parent) {
  48298. return _super.prototype._serialize.call(this, {
  48299. name: "SetParentAction",
  48300. properties: [
  48301. BABYLON.Action._GetTargetProperty(this._target),
  48302. BABYLON.Action._GetTargetProperty(this._parent),
  48303. ]
  48304. }, parent);
  48305. };
  48306. return SetParentAction;
  48307. }(BABYLON.Action));
  48308. BABYLON.SetParentAction = SetParentAction;
  48309. var PlaySoundAction = /** @class */ (function (_super) {
  48310. __extends(PlaySoundAction, _super);
  48311. function PlaySoundAction(triggerOptions, sound, condition) {
  48312. var _this = _super.call(this, triggerOptions, condition) || this;
  48313. _this._sound = sound;
  48314. return _this;
  48315. }
  48316. PlaySoundAction.prototype._prepare = function () {
  48317. };
  48318. PlaySoundAction.prototype.execute = function () {
  48319. if (this._sound !== undefined)
  48320. this._sound.play();
  48321. };
  48322. PlaySoundAction.prototype.serialize = function (parent) {
  48323. return _super.prototype._serialize.call(this, {
  48324. name: "PlaySoundAction",
  48325. properties: [{ name: "sound", value: this._sound.name }]
  48326. }, parent);
  48327. };
  48328. return PlaySoundAction;
  48329. }(BABYLON.Action));
  48330. BABYLON.PlaySoundAction = PlaySoundAction;
  48331. var StopSoundAction = /** @class */ (function (_super) {
  48332. __extends(StopSoundAction, _super);
  48333. function StopSoundAction(triggerOptions, sound, condition) {
  48334. var _this = _super.call(this, triggerOptions, condition) || this;
  48335. _this._sound = sound;
  48336. return _this;
  48337. }
  48338. StopSoundAction.prototype._prepare = function () {
  48339. };
  48340. StopSoundAction.prototype.execute = function () {
  48341. if (this._sound !== undefined)
  48342. this._sound.stop();
  48343. };
  48344. StopSoundAction.prototype.serialize = function (parent) {
  48345. return _super.prototype._serialize.call(this, {
  48346. name: "StopSoundAction",
  48347. properties: [{ name: "sound", value: this._sound.name }]
  48348. }, parent);
  48349. };
  48350. return StopSoundAction;
  48351. }(BABYLON.Action));
  48352. BABYLON.StopSoundAction = StopSoundAction;
  48353. })(BABYLON || (BABYLON = {}));
  48354. //# sourceMappingURL=babylon.directActions.js.map
  48355. var BABYLON;
  48356. (function (BABYLON) {
  48357. var SpriteManager = /** @class */ (function () {
  48358. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48359. if (epsilon === void 0) { epsilon = 0.01; }
  48360. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48361. this.name = name;
  48362. this.sprites = new Array();
  48363. this.renderingGroupId = 0;
  48364. this.layerMask = 0x0FFFFFFF;
  48365. this.fogEnabled = true;
  48366. this.isPickable = false;
  48367. /**
  48368. * An event triggered when the manager is disposed.
  48369. * @type {BABYLON.Observable}
  48370. */
  48371. this.onDisposeObservable = new BABYLON.Observable();
  48372. this._vertexBuffers = {};
  48373. this._capacity = capacity;
  48374. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48375. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48376. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48377. if (cellSize.width && cellSize.height) {
  48378. this.cellWidth = cellSize.width;
  48379. this.cellHeight = cellSize.height;
  48380. }
  48381. else if (cellSize !== undefined) {
  48382. this.cellWidth = cellSize;
  48383. this.cellHeight = cellSize;
  48384. }
  48385. else {
  48386. return;
  48387. }
  48388. this._epsilon = epsilon;
  48389. this._scene = scene;
  48390. this._scene.spriteManagers.push(this);
  48391. var indices = [];
  48392. var index = 0;
  48393. for (var count = 0; count < capacity; count++) {
  48394. indices.push(index);
  48395. indices.push(index + 1);
  48396. indices.push(index + 2);
  48397. indices.push(index);
  48398. indices.push(index + 2);
  48399. indices.push(index + 3);
  48400. index += 4;
  48401. }
  48402. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48403. // VBO
  48404. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48405. this._vertexData = new Float32Array(capacity * 16 * 4);
  48406. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48407. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48408. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48409. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48410. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48411. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48412. this._vertexBuffers["options"] = options;
  48413. this._vertexBuffers["cellInfo"] = cellInfo;
  48414. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48415. // Effects
  48416. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48417. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48418. }
  48419. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48420. set: function (callback) {
  48421. if (this._onDisposeObserver) {
  48422. this.onDisposeObservable.remove(this._onDisposeObserver);
  48423. }
  48424. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48425. },
  48426. enumerable: true,
  48427. configurable: true
  48428. });
  48429. Object.defineProperty(SpriteManager.prototype, "texture", {
  48430. get: function () {
  48431. return this._spriteTexture;
  48432. },
  48433. set: function (value) {
  48434. this._spriteTexture = value;
  48435. },
  48436. enumerable: true,
  48437. configurable: true
  48438. });
  48439. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48440. var arrayOffset = index * 16;
  48441. if (offsetX === 0)
  48442. offsetX = this._epsilon;
  48443. else if (offsetX === 1)
  48444. offsetX = 1 - this._epsilon;
  48445. if (offsetY === 0)
  48446. offsetY = this._epsilon;
  48447. else if (offsetY === 1)
  48448. offsetY = 1 - this._epsilon;
  48449. this._vertexData[arrayOffset] = sprite.position.x;
  48450. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48451. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48452. this._vertexData[arrayOffset + 3] = sprite.angle;
  48453. this._vertexData[arrayOffset + 4] = sprite.width;
  48454. this._vertexData[arrayOffset + 5] = sprite.height;
  48455. this._vertexData[arrayOffset + 6] = offsetX;
  48456. this._vertexData[arrayOffset + 7] = offsetY;
  48457. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48458. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48459. var offset = (sprite.cellIndex / rowSize) >> 0;
  48460. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48461. this._vertexData[arrayOffset + 11] = offset;
  48462. // Color
  48463. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48464. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48465. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48466. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48467. };
  48468. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48469. var count = Math.min(this._capacity, this.sprites.length);
  48470. var min = BABYLON.Vector3.Zero();
  48471. var max = BABYLON.Vector3.Zero();
  48472. var distance = Number.MAX_VALUE;
  48473. var currentSprite = null;
  48474. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48475. var cameraView = camera.getViewMatrix();
  48476. for (var index = 0; index < count; index++) {
  48477. var sprite = this.sprites[index];
  48478. if (!sprite) {
  48479. continue;
  48480. }
  48481. if (predicate) {
  48482. if (!predicate(sprite)) {
  48483. continue;
  48484. }
  48485. }
  48486. else if (!sprite.isPickable) {
  48487. continue;
  48488. }
  48489. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48490. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48491. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48492. if (ray.intersectsBoxMinMax(min, max)) {
  48493. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48494. if (distance > currentDistance) {
  48495. distance = currentDistance;
  48496. currentSprite = sprite;
  48497. if (fastCheck) {
  48498. break;
  48499. }
  48500. }
  48501. }
  48502. }
  48503. if (currentSprite) {
  48504. var result = new BABYLON.PickingInfo();
  48505. result.hit = true;
  48506. result.pickedSprite = currentSprite;
  48507. result.distance = distance;
  48508. return result;
  48509. }
  48510. return null;
  48511. };
  48512. SpriteManager.prototype.render = function () {
  48513. // Check
  48514. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48515. return;
  48516. var engine = this._scene.getEngine();
  48517. var baseSize = this._spriteTexture.getBaseSize();
  48518. // Sprites
  48519. var deltaTime = engine.getDeltaTime();
  48520. var max = Math.min(this._capacity, this.sprites.length);
  48521. var rowSize = baseSize.width / this.cellWidth;
  48522. var offset = 0;
  48523. for (var index = 0; index < max; index++) {
  48524. var sprite = this.sprites[index];
  48525. if (!sprite) {
  48526. continue;
  48527. }
  48528. sprite._animate(deltaTime);
  48529. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48530. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48531. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48532. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48533. }
  48534. this._buffer.update(this._vertexData);
  48535. // Render
  48536. var effect = this._effectBase;
  48537. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48538. effect = this._effectFog;
  48539. }
  48540. engine.enableEffect(effect);
  48541. var viewMatrix = this._scene.getViewMatrix();
  48542. effect.setTexture("diffuseSampler", this._spriteTexture);
  48543. effect.setMatrix("view", viewMatrix);
  48544. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48545. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48546. // Fog
  48547. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48548. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48549. effect.setColor3("vFogColor", this._scene.fogColor);
  48550. }
  48551. // VBOs
  48552. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48553. // Draw order
  48554. engine.setDepthFunctionToLessOrEqual();
  48555. effect.setBool("alphaTest", true);
  48556. engine.setColorWrite(false);
  48557. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48558. engine.setColorWrite(true);
  48559. effect.setBool("alphaTest", false);
  48560. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48561. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48562. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48563. };
  48564. SpriteManager.prototype.dispose = function () {
  48565. if (this._buffer) {
  48566. this._buffer.dispose();
  48567. this._buffer = null;
  48568. }
  48569. if (this._indexBuffer) {
  48570. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48571. this._indexBuffer = null;
  48572. }
  48573. if (this._spriteTexture) {
  48574. this._spriteTexture.dispose();
  48575. this._spriteTexture = null;
  48576. }
  48577. // Remove from scene
  48578. var index = this._scene.spriteManagers.indexOf(this);
  48579. this._scene.spriteManagers.splice(index, 1);
  48580. // Callback
  48581. this.onDisposeObservable.notifyObservers(this);
  48582. this.onDisposeObservable.clear();
  48583. };
  48584. return SpriteManager;
  48585. }());
  48586. BABYLON.SpriteManager = SpriteManager;
  48587. })(BABYLON || (BABYLON = {}));
  48588. //# sourceMappingURL=babylon.spriteManager.js.map
  48589. var BABYLON;
  48590. (function (BABYLON) {
  48591. var Sprite = /** @class */ (function () {
  48592. function Sprite(name, manager) {
  48593. this.name = name;
  48594. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48595. this.width = 1.0;
  48596. this.height = 1.0;
  48597. this.angle = 0;
  48598. this.cellIndex = 0;
  48599. this.invertU = 0;
  48600. this.invertV = 0;
  48601. this.animations = new Array();
  48602. this.isPickable = false;
  48603. this._animationStarted = false;
  48604. this._loopAnimation = false;
  48605. this._fromIndex = 0;
  48606. this._toIndex = 0;
  48607. this._delay = 0;
  48608. this._direction = 1;
  48609. this._time = 0;
  48610. this._manager = manager;
  48611. this._manager.sprites.push(this);
  48612. this.position = BABYLON.Vector3.Zero();
  48613. }
  48614. Object.defineProperty(Sprite.prototype, "size", {
  48615. get: function () {
  48616. return this.width;
  48617. },
  48618. set: function (value) {
  48619. this.width = value;
  48620. this.height = value;
  48621. },
  48622. enumerable: true,
  48623. configurable: true
  48624. });
  48625. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  48626. this._fromIndex = from;
  48627. this._toIndex = to;
  48628. this._loopAnimation = loop;
  48629. this._delay = delay;
  48630. this._animationStarted = true;
  48631. this._direction = from < to ? 1 : -1;
  48632. this.cellIndex = from;
  48633. this._time = 0;
  48634. this._onAnimationEnd = onAnimationEnd;
  48635. };
  48636. Sprite.prototype.stopAnimation = function () {
  48637. this._animationStarted = false;
  48638. };
  48639. Sprite.prototype._animate = function (deltaTime) {
  48640. if (!this._animationStarted)
  48641. return;
  48642. this._time += deltaTime;
  48643. if (this._time > this._delay) {
  48644. this._time = this._time % this._delay;
  48645. this.cellIndex += this._direction;
  48646. if (this.cellIndex > this._toIndex) {
  48647. if (this._loopAnimation) {
  48648. this.cellIndex = this._fromIndex;
  48649. }
  48650. else {
  48651. this.cellIndex = this._toIndex;
  48652. this._animationStarted = false;
  48653. if (this._onAnimationEnd) {
  48654. this._onAnimationEnd();
  48655. }
  48656. if (this.disposeWhenFinishedAnimating) {
  48657. this.dispose();
  48658. }
  48659. }
  48660. }
  48661. }
  48662. };
  48663. Sprite.prototype.dispose = function () {
  48664. for (var i = 0; i < this._manager.sprites.length; i++) {
  48665. if (this._manager.sprites[i] == this) {
  48666. this._manager.sprites.splice(i, 1);
  48667. }
  48668. }
  48669. };
  48670. return Sprite;
  48671. }());
  48672. BABYLON.Sprite = Sprite;
  48673. })(BABYLON || (BABYLON = {}));
  48674. //# sourceMappingURL=babylon.sprite.js.map
  48675. var BABYLON;
  48676. (function (BABYLON) {
  48677. var IntersectionInfo = /** @class */ (function () {
  48678. function IntersectionInfo(bu, bv, distance) {
  48679. this.bu = bu;
  48680. this.bv = bv;
  48681. this.distance = distance;
  48682. this.faceId = 0;
  48683. this.subMeshId = 0;
  48684. }
  48685. return IntersectionInfo;
  48686. }());
  48687. BABYLON.IntersectionInfo = IntersectionInfo;
  48688. var PickingInfo = /** @class */ (function () {
  48689. function PickingInfo() {
  48690. this.hit = false;
  48691. this.distance = 0;
  48692. this.pickedPoint = null;
  48693. this.pickedMesh = null;
  48694. this.bu = 0;
  48695. this.bv = 0;
  48696. this.faceId = -1;
  48697. this.subMeshId = 0;
  48698. this.pickedSprite = null;
  48699. }
  48700. // Methods
  48701. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  48702. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  48703. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  48704. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  48705. return null;
  48706. }
  48707. var indices = this.pickedMesh.getIndices();
  48708. if (!indices) {
  48709. return null;
  48710. }
  48711. var result;
  48712. if (useVerticesNormals) {
  48713. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48714. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  48715. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  48716. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  48717. normal0 = normal0.scale(this.bu);
  48718. normal1 = normal1.scale(this.bv);
  48719. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  48720. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  48721. }
  48722. else {
  48723. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48724. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  48725. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  48726. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  48727. var p1p2 = vertex1.subtract(vertex2);
  48728. var p3p2 = vertex3.subtract(vertex2);
  48729. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  48730. }
  48731. if (useWorldCoordinates) {
  48732. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  48733. }
  48734. return BABYLON.Vector3.Normalize(result);
  48735. };
  48736. PickingInfo.prototype.getTextureCoordinates = function () {
  48737. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48738. return null;
  48739. }
  48740. var indices = this.pickedMesh.getIndices();
  48741. if (!indices) {
  48742. return null;
  48743. }
  48744. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48745. if (!uvs) {
  48746. return null;
  48747. }
  48748. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  48749. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  48750. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  48751. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  48752. uv1 = uv1.scale(this.bu);
  48753. uv2 = uv2.scale(this.bv);
  48754. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  48755. };
  48756. return PickingInfo;
  48757. }());
  48758. BABYLON.PickingInfo = PickingInfo;
  48759. })(BABYLON || (BABYLON = {}));
  48760. //# sourceMappingURL=babylon.pickingInfo.js.map
  48761. var BABYLON;
  48762. (function (BABYLON) {
  48763. var Ray = /** @class */ (function () {
  48764. function Ray(origin, direction, length) {
  48765. if (length === void 0) { length = Number.MAX_VALUE; }
  48766. this.origin = origin;
  48767. this.direction = direction;
  48768. this.length = length;
  48769. }
  48770. // Methods
  48771. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  48772. var d = 0.0;
  48773. var maxValue = Number.MAX_VALUE;
  48774. var inv;
  48775. var min;
  48776. var max;
  48777. var temp;
  48778. if (Math.abs(this.direction.x) < 0.0000001) {
  48779. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  48780. return false;
  48781. }
  48782. }
  48783. else {
  48784. inv = 1.0 / this.direction.x;
  48785. min = (minimum.x - this.origin.x) * inv;
  48786. max = (maximum.x - this.origin.x) * inv;
  48787. if (max === -Infinity) {
  48788. max = Infinity;
  48789. }
  48790. if (min > max) {
  48791. temp = min;
  48792. min = max;
  48793. max = temp;
  48794. }
  48795. d = Math.max(min, d);
  48796. maxValue = Math.min(max, maxValue);
  48797. if (d > maxValue) {
  48798. return false;
  48799. }
  48800. }
  48801. if (Math.abs(this.direction.y) < 0.0000001) {
  48802. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  48803. return false;
  48804. }
  48805. }
  48806. else {
  48807. inv = 1.0 / this.direction.y;
  48808. min = (minimum.y - this.origin.y) * inv;
  48809. max = (maximum.y - this.origin.y) * inv;
  48810. if (max === -Infinity) {
  48811. max = Infinity;
  48812. }
  48813. if (min > max) {
  48814. temp = min;
  48815. min = max;
  48816. max = temp;
  48817. }
  48818. d = Math.max(min, d);
  48819. maxValue = Math.min(max, maxValue);
  48820. if (d > maxValue) {
  48821. return false;
  48822. }
  48823. }
  48824. if (Math.abs(this.direction.z) < 0.0000001) {
  48825. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  48826. return false;
  48827. }
  48828. }
  48829. else {
  48830. inv = 1.0 / this.direction.z;
  48831. min = (minimum.z - this.origin.z) * inv;
  48832. max = (maximum.z - this.origin.z) * inv;
  48833. if (max === -Infinity) {
  48834. max = Infinity;
  48835. }
  48836. if (min > max) {
  48837. temp = min;
  48838. min = max;
  48839. max = temp;
  48840. }
  48841. d = Math.max(min, d);
  48842. maxValue = Math.min(max, maxValue);
  48843. if (d > maxValue) {
  48844. return false;
  48845. }
  48846. }
  48847. return true;
  48848. };
  48849. Ray.prototype.intersectsBox = function (box) {
  48850. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  48851. };
  48852. Ray.prototype.intersectsSphere = function (sphere) {
  48853. var x = sphere.center.x - this.origin.x;
  48854. var y = sphere.center.y - this.origin.y;
  48855. var z = sphere.center.z - this.origin.z;
  48856. var pyth = (x * x) + (y * y) + (z * z);
  48857. var rr = sphere.radius * sphere.radius;
  48858. if (pyth <= rr) {
  48859. return true;
  48860. }
  48861. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  48862. if (dot < 0.0) {
  48863. return false;
  48864. }
  48865. var temp = pyth - (dot * dot);
  48866. return temp <= rr;
  48867. };
  48868. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  48869. if (!this._edge1) {
  48870. this._edge1 = BABYLON.Vector3.Zero();
  48871. this._edge2 = BABYLON.Vector3.Zero();
  48872. this._pvec = BABYLON.Vector3.Zero();
  48873. this._tvec = BABYLON.Vector3.Zero();
  48874. this._qvec = BABYLON.Vector3.Zero();
  48875. }
  48876. vertex1.subtractToRef(vertex0, this._edge1);
  48877. vertex2.subtractToRef(vertex0, this._edge2);
  48878. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  48879. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  48880. if (det === 0) {
  48881. return null;
  48882. }
  48883. var invdet = 1 / det;
  48884. this.origin.subtractToRef(vertex0, this._tvec);
  48885. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  48886. if (bu < 0 || bu > 1.0) {
  48887. return null;
  48888. }
  48889. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  48890. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  48891. if (bv < 0 || bu + bv > 1.0) {
  48892. return null;
  48893. }
  48894. //check if the distance is longer than the predefined length.
  48895. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  48896. if (distance > this.length) {
  48897. return null;
  48898. }
  48899. return new BABYLON.IntersectionInfo(bu, bv, distance);
  48900. };
  48901. Ray.prototype.intersectsPlane = function (plane) {
  48902. var distance;
  48903. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  48904. if (Math.abs(result1) < 9.99999997475243E-07) {
  48905. return null;
  48906. }
  48907. else {
  48908. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  48909. distance = (-plane.d - result2) / result1;
  48910. if (distance < 0.0) {
  48911. if (distance < -9.99999997475243E-07) {
  48912. return null;
  48913. }
  48914. else {
  48915. return 0;
  48916. }
  48917. }
  48918. return distance;
  48919. }
  48920. };
  48921. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  48922. var tm = BABYLON.Tmp.Matrix[0];
  48923. mesh.getWorldMatrix().invertToRef(tm);
  48924. if (this._tmpRay) {
  48925. Ray.TransformToRef(this, tm, this._tmpRay);
  48926. }
  48927. else {
  48928. this._tmpRay = Ray.Transform(this, tm);
  48929. }
  48930. return mesh.intersects(this._tmpRay, fastCheck);
  48931. };
  48932. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  48933. if (results) {
  48934. results.length = 0;
  48935. }
  48936. else {
  48937. results = [];
  48938. }
  48939. for (var i = 0; i < meshes.length; i++) {
  48940. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  48941. if (pickInfo.hit) {
  48942. results.push(pickInfo);
  48943. }
  48944. }
  48945. results.sort(this._comparePickingInfo);
  48946. return results;
  48947. };
  48948. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  48949. if (pickingInfoA.distance < pickingInfoB.distance) {
  48950. return -1;
  48951. }
  48952. else if (pickingInfoA.distance > pickingInfoB.distance) {
  48953. return 1;
  48954. }
  48955. else {
  48956. return 0;
  48957. }
  48958. };
  48959. /**
  48960. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  48961. * @param sega the first point of the segment to test the intersection against
  48962. * @param segb the second point of the segment to test the intersection against
  48963. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  48964. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  48965. */
  48966. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  48967. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  48968. var u = segb.subtract(sega);
  48969. var v = rsegb.subtract(this.origin);
  48970. var w = sega.subtract(this.origin);
  48971. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  48972. var b = BABYLON.Vector3.Dot(u, v);
  48973. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  48974. var d = BABYLON.Vector3.Dot(u, w);
  48975. var e = BABYLON.Vector3.Dot(v, w);
  48976. var D = a * c - b * b; // always >= 0
  48977. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  48978. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  48979. // compute the line parameters of the two closest points
  48980. if (D < Ray.smallnum) {
  48981. sN = 0.0; // force using point P0 on segment S1
  48982. sD = 1.0; // to prevent possible division by 0.0 later
  48983. tN = e;
  48984. tD = c;
  48985. }
  48986. else {
  48987. sN = (b * e - c * d);
  48988. tN = (a * e - b * d);
  48989. if (sN < 0.0) {
  48990. sN = 0.0;
  48991. tN = e;
  48992. tD = c;
  48993. }
  48994. else if (sN > sD) {
  48995. sN = sD;
  48996. tN = e + b;
  48997. tD = c;
  48998. }
  48999. }
  49000. if (tN < 0.0) {
  49001. tN = 0.0;
  49002. // recompute sc for this edge
  49003. if (-d < 0.0) {
  49004. sN = 0.0;
  49005. }
  49006. else if (-d > a)
  49007. sN = sD;
  49008. else {
  49009. sN = -d;
  49010. sD = a;
  49011. }
  49012. }
  49013. else if (tN > tD) {
  49014. tN = tD;
  49015. // recompute sc for this edge
  49016. if ((-d + b) < 0.0) {
  49017. sN = 0;
  49018. }
  49019. else if ((-d + b) > a) {
  49020. sN = sD;
  49021. }
  49022. else {
  49023. sN = (-d + b);
  49024. sD = a;
  49025. }
  49026. }
  49027. // finally do the division to get sc and tc
  49028. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49029. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49030. // get the difference of the two closest points
  49031. var qtc = v.multiplyByFloats(tc, tc, tc);
  49032. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49033. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49034. if (isIntersected) {
  49035. return qtc.length();
  49036. }
  49037. return -1;
  49038. };
  49039. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49040. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49041. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49042. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49043. this.direction.normalize();
  49044. return this;
  49045. };
  49046. // Statics
  49047. Ray.Zero = function () {
  49048. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49049. };
  49050. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49051. var result = Ray.Zero();
  49052. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49053. };
  49054. /**
  49055. * 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
  49056. * transformed to the given world matrix.
  49057. * @param origin The origin point
  49058. * @param end The end point
  49059. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49060. */
  49061. Ray.CreateNewFromTo = function (origin, end, world) {
  49062. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49063. var direction = end.subtract(origin);
  49064. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49065. direction.normalize();
  49066. return Ray.Transform(new Ray(origin, direction, length), world);
  49067. };
  49068. Ray.Transform = function (ray, matrix) {
  49069. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49070. Ray.TransformToRef(ray, matrix, result);
  49071. return result;
  49072. };
  49073. Ray.TransformToRef = function (ray, matrix, result) {
  49074. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49075. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49076. result.length = ray.length;
  49077. var dir = result.direction;
  49078. var len = dir.length();
  49079. if (!(len === 0 || len === 1)) {
  49080. var num = 1.0 / len;
  49081. dir.x *= num;
  49082. dir.y *= num;
  49083. dir.z *= num;
  49084. result.length *= len;
  49085. }
  49086. };
  49087. Ray.smallnum = 0.00000001;
  49088. Ray.rayl = 10e8;
  49089. return Ray;
  49090. }());
  49091. BABYLON.Ray = Ray;
  49092. })(BABYLON || (BABYLON = {}));
  49093. //# sourceMappingURL=babylon.ray.js.map
  49094. var BABYLON;
  49095. (function (BABYLON) {
  49096. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49097. if (boxMin.x > sphereCenter.x + sphereRadius)
  49098. return false;
  49099. if (sphereCenter.x - sphereRadius > boxMax.x)
  49100. return false;
  49101. if (boxMin.y > sphereCenter.y + sphereRadius)
  49102. return false;
  49103. if (sphereCenter.y - sphereRadius > boxMax.y)
  49104. return false;
  49105. if (boxMin.z > sphereCenter.z + sphereRadius)
  49106. return false;
  49107. if (sphereCenter.z - sphereRadius > boxMax.z)
  49108. return false;
  49109. return true;
  49110. };
  49111. var getLowestRoot = (function () {
  49112. var result = { root: 0, found: false };
  49113. return function (a, b, c, maxR) {
  49114. result.root = 0;
  49115. result.found = false;
  49116. var determinant = b * b - 4.0 * a * c;
  49117. if (determinant < 0)
  49118. return result;
  49119. var sqrtD = Math.sqrt(determinant);
  49120. var r1 = (-b - sqrtD) / (2.0 * a);
  49121. var r2 = (-b + sqrtD) / (2.0 * a);
  49122. if (r1 > r2) {
  49123. var temp = r2;
  49124. r2 = r1;
  49125. r1 = temp;
  49126. }
  49127. if (r1 > 0 && r1 < maxR) {
  49128. result.root = r1;
  49129. result.found = true;
  49130. return result;
  49131. }
  49132. if (r2 > 0 && r2 < maxR) {
  49133. result.root = r2;
  49134. result.found = true;
  49135. return result;
  49136. }
  49137. return result;
  49138. };
  49139. })();
  49140. var Collider = /** @class */ (function () {
  49141. function Collider() {
  49142. this._collisionPoint = BABYLON.Vector3.Zero();
  49143. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49144. this._tempVector = BABYLON.Vector3.Zero();
  49145. this._tempVector2 = BABYLON.Vector3.Zero();
  49146. this._tempVector3 = BABYLON.Vector3.Zero();
  49147. this._tempVector4 = BABYLON.Vector3.Zero();
  49148. this._edge = BABYLON.Vector3.Zero();
  49149. this._baseToVertex = BABYLON.Vector3.Zero();
  49150. this._destinationPoint = BABYLON.Vector3.Zero();
  49151. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49152. this._displacementVector = BABYLON.Vector3.Zero();
  49153. this._radius = BABYLON.Vector3.One();
  49154. this._retry = 0;
  49155. this._basePointWorld = BABYLON.Vector3.Zero();
  49156. this._velocityWorld = BABYLON.Vector3.Zero();
  49157. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49158. this._collisionMask = -1;
  49159. }
  49160. Object.defineProperty(Collider.prototype, "collisionMask", {
  49161. get: function () {
  49162. return this._collisionMask;
  49163. },
  49164. set: function (mask) {
  49165. this._collisionMask = !isNaN(mask) ? mask : -1;
  49166. },
  49167. enumerable: true,
  49168. configurable: true
  49169. });
  49170. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49171. /**
  49172. * Gets the plane normal used to compute the sliding response (in local space)
  49173. */
  49174. get: function () {
  49175. return this._slidePlaneNormal;
  49176. },
  49177. enumerable: true,
  49178. configurable: true
  49179. });
  49180. // Methods
  49181. Collider.prototype._initialize = function (source, dir, e) {
  49182. this._velocity = dir;
  49183. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49184. this._basePoint = source;
  49185. source.multiplyToRef(this._radius, this._basePointWorld);
  49186. dir.multiplyToRef(this._radius, this._velocityWorld);
  49187. this._velocityWorldLength = this._velocityWorld.length();
  49188. this._epsilon = e;
  49189. this.collisionFound = false;
  49190. };
  49191. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49192. pa.subtractToRef(point, this._tempVector);
  49193. pb.subtractToRef(point, this._tempVector2);
  49194. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49195. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49196. if (d < 0)
  49197. return false;
  49198. pc.subtractToRef(point, this._tempVector3);
  49199. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49200. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49201. if (d < 0)
  49202. return false;
  49203. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49204. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49205. return d >= 0;
  49206. };
  49207. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49208. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49209. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49210. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49211. return false;
  49212. }
  49213. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49214. return false;
  49215. return true;
  49216. };
  49217. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49218. var t0;
  49219. var embeddedInPlane = false;
  49220. //defensive programming, actually not needed.
  49221. if (!trianglePlaneArray) {
  49222. trianglePlaneArray = [];
  49223. }
  49224. if (!trianglePlaneArray[faceIndex]) {
  49225. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49226. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49227. }
  49228. var trianglePlane = trianglePlaneArray[faceIndex];
  49229. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49230. return;
  49231. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49232. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49233. if (normalDotVelocity == 0) {
  49234. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49235. return;
  49236. embeddedInPlane = true;
  49237. t0 = 0;
  49238. }
  49239. else {
  49240. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49241. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49242. if (t0 > t1) {
  49243. var temp = t1;
  49244. t1 = t0;
  49245. t0 = temp;
  49246. }
  49247. if (t0 > 1.0 || t1 < 0.0)
  49248. return;
  49249. if (t0 < 0)
  49250. t0 = 0;
  49251. if (t0 > 1.0)
  49252. t0 = 1.0;
  49253. }
  49254. this._collisionPoint.copyFromFloats(0, 0, 0);
  49255. var found = false;
  49256. var t = 1.0;
  49257. if (!embeddedInPlane) {
  49258. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49259. this._velocity.scaleToRef(t0, this._tempVector);
  49260. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49261. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49262. found = true;
  49263. t = t0;
  49264. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49265. }
  49266. }
  49267. if (!found) {
  49268. var velocitySquaredLength = this._velocity.lengthSquared();
  49269. var a = velocitySquaredLength;
  49270. this._basePoint.subtractToRef(p1, this._tempVector);
  49271. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49272. var c = this._tempVector.lengthSquared() - 1.0;
  49273. var lowestRoot = getLowestRoot(a, b, c, t);
  49274. if (lowestRoot.found) {
  49275. t = lowestRoot.root;
  49276. found = true;
  49277. this._collisionPoint.copyFrom(p1);
  49278. }
  49279. this._basePoint.subtractToRef(p2, this._tempVector);
  49280. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49281. c = this._tempVector.lengthSquared() - 1.0;
  49282. lowestRoot = getLowestRoot(a, b, c, t);
  49283. if (lowestRoot.found) {
  49284. t = lowestRoot.root;
  49285. found = true;
  49286. this._collisionPoint.copyFrom(p2);
  49287. }
  49288. this._basePoint.subtractToRef(p3, this._tempVector);
  49289. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49290. c = this._tempVector.lengthSquared() - 1.0;
  49291. lowestRoot = getLowestRoot(a, b, c, t);
  49292. if (lowestRoot.found) {
  49293. t = lowestRoot.root;
  49294. found = true;
  49295. this._collisionPoint.copyFrom(p3);
  49296. }
  49297. p2.subtractToRef(p1, this._edge);
  49298. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49299. var edgeSquaredLength = this._edge.lengthSquared();
  49300. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49301. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49302. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49303. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49304. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49305. lowestRoot = getLowestRoot(a, b, c, t);
  49306. if (lowestRoot.found) {
  49307. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49308. if (f >= 0.0 && f <= 1.0) {
  49309. t = lowestRoot.root;
  49310. found = true;
  49311. this._edge.scaleInPlace(f);
  49312. p1.addToRef(this._edge, this._collisionPoint);
  49313. }
  49314. }
  49315. p3.subtractToRef(p2, this._edge);
  49316. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49317. edgeSquaredLength = this._edge.lengthSquared();
  49318. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49319. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49320. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49321. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49322. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49323. lowestRoot = getLowestRoot(a, b, c, t);
  49324. if (lowestRoot.found) {
  49325. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49326. if (f >= 0.0 && f <= 1.0) {
  49327. t = lowestRoot.root;
  49328. found = true;
  49329. this._edge.scaleInPlace(f);
  49330. p2.addToRef(this._edge, this._collisionPoint);
  49331. }
  49332. }
  49333. p1.subtractToRef(p3, this._edge);
  49334. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49335. edgeSquaredLength = this._edge.lengthSquared();
  49336. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49337. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49338. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49339. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49340. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49341. lowestRoot = getLowestRoot(a, b, c, t);
  49342. if (lowestRoot.found) {
  49343. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49344. if (f >= 0.0 && f <= 1.0) {
  49345. t = lowestRoot.root;
  49346. found = true;
  49347. this._edge.scaleInPlace(f);
  49348. p3.addToRef(this._edge, this._collisionPoint);
  49349. }
  49350. }
  49351. }
  49352. if (found) {
  49353. var distToCollision = t * this._velocity.length();
  49354. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49355. if (!this.intersectionPoint) {
  49356. this.intersectionPoint = this._collisionPoint.clone();
  49357. }
  49358. else {
  49359. this.intersectionPoint.copyFrom(this._collisionPoint);
  49360. }
  49361. this._nearestDistance = distToCollision;
  49362. this.collisionFound = true;
  49363. }
  49364. }
  49365. };
  49366. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49367. for (var i = indexStart; i < indexEnd; i += 3) {
  49368. var p1 = pts[indices[i] - decal];
  49369. var p2 = pts[indices[i + 1] - decal];
  49370. var p3 = pts[indices[i + 2] - decal];
  49371. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49372. }
  49373. };
  49374. Collider.prototype._getResponse = function (pos, vel) {
  49375. pos.addToRef(vel, this._destinationPoint);
  49376. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49377. this._basePoint.addToRef(vel, pos);
  49378. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49379. this._slidePlaneNormal.normalize();
  49380. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49381. pos.addInPlace(this._displacementVector);
  49382. this.intersectionPoint.addInPlace(this._displacementVector);
  49383. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49384. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49385. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49386. };
  49387. return Collider;
  49388. }());
  49389. BABYLON.Collider = Collider;
  49390. })(BABYLON || (BABYLON = {}));
  49391. //# sourceMappingURL=babylon.collider.js.map
  49392. var BABYLON;
  49393. (function (BABYLON) {
  49394. //WebWorker code will be inserted to this variable.
  49395. BABYLON.CollisionWorker = "";
  49396. var WorkerTaskType;
  49397. (function (WorkerTaskType) {
  49398. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49399. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49400. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49401. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49402. var WorkerReplyType;
  49403. (function (WorkerReplyType) {
  49404. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49405. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49406. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49407. var CollisionCoordinatorWorker = /** @class */ (function () {
  49408. function CollisionCoordinatorWorker() {
  49409. var _this = this;
  49410. this._scaledPosition = BABYLON.Vector3.Zero();
  49411. this._scaledVelocity = BABYLON.Vector3.Zero();
  49412. this.onMeshUpdated = function (transformNode) {
  49413. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49414. };
  49415. this.onGeometryUpdated = function (geometry) {
  49416. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49417. };
  49418. this._afterRender = function () {
  49419. if (!_this._init)
  49420. return;
  49421. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49422. return;
  49423. }
  49424. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49425. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49426. if (_this._runningUpdated > 4) {
  49427. return;
  49428. }
  49429. ++_this._runningUpdated;
  49430. var payload = {
  49431. updatedMeshes: _this._addUpdateMeshesList,
  49432. updatedGeometries: _this._addUpdateGeometriesList,
  49433. removedGeometries: _this._toRemoveGeometryArray,
  49434. removedMeshes: _this._toRemoveMeshesArray
  49435. };
  49436. var message = {
  49437. payload: payload,
  49438. taskType: WorkerTaskType.UPDATE
  49439. };
  49440. var serializable = [];
  49441. for (var id in payload.updatedGeometries) {
  49442. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49443. //prepare transferables
  49444. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49445. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49446. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49447. }
  49448. }
  49449. _this._worker.postMessage(message, serializable);
  49450. _this._addUpdateMeshesList = {};
  49451. _this._addUpdateGeometriesList = {};
  49452. _this._toRemoveGeometryArray = [];
  49453. _this._toRemoveMeshesArray = [];
  49454. };
  49455. this._onMessageFromWorker = function (e) {
  49456. var returnData = e.data;
  49457. if (returnData.error != WorkerReplyType.SUCCESS) {
  49458. //TODO what errors can be returned from the worker?
  49459. BABYLON.Tools.Warn("error returned from worker!");
  49460. return;
  49461. }
  49462. switch (returnData.taskType) {
  49463. case WorkerTaskType.INIT:
  49464. _this._init = true;
  49465. //Update the worked with ALL of the scene's current state
  49466. _this._scene.meshes.forEach(function (mesh) {
  49467. _this.onMeshAdded(mesh);
  49468. });
  49469. _this._scene.getGeometries().forEach(function (geometry) {
  49470. _this.onGeometryAdded(geometry);
  49471. });
  49472. break;
  49473. case WorkerTaskType.UPDATE:
  49474. _this._runningUpdated--;
  49475. break;
  49476. case WorkerTaskType.COLLIDE:
  49477. var returnPayload = returnData.payload;
  49478. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49479. return;
  49480. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49481. if (callback) {
  49482. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49483. if (mesh) {
  49484. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49485. }
  49486. }
  49487. //cleanup
  49488. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49489. break;
  49490. }
  49491. };
  49492. this._collisionsCallbackArray = [];
  49493. this._init = false;
  49494. this._runningUpdated = 0;
  49495. this._addUpdateMeshesList = {};
  49496. this._addUpdateGeometriesList = {};
  49497. this._toRemoveGeometryArray = [];
  49498. this._toRemoveMeshesArray = [];
  49499. }
  49500. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49501. if (!this._init)
  49502. return;
  49503. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49504. return;
  49505. position.divideToRef(collider._radius, this._scaledPosition);
  49506. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49507. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49508. var payload = {
  49509. collider: {
  49510. position: this._scaledPosition.asArray(),
  49511. velocity: this._scaledVelocity.asArray(),
  49512. radius: collider._radius.asArray()
  49513. },
  49514. collisionId: collisionIndex,
  49515. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49516. maximumRetry: maximumRetry
  49517. };
  49518. var message = {
  49519. payload: payload,
  49520. taskType: WorkerTaskType.COLLIDE
  49521. };
  49522. this._worker.postMessage(message);
  49523. };
  49524. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49525. this._scene = scene;
  49526. this._scene.registerAfterRender(this._afterRender);
  49527. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49528. this._worker = new Worker(workerUrl);
  49529. this._worker.onmessage = this._onMessageFromWorker;
  49530. var message = {
  49531. payload: {},
  49532. taskType: WorkerTaskType.INIT
  49533. };
  49534. this._worker.postMessage(message);
  49535. };
  49536. CollisionCoordinatorWorker.prototype.destroy = function () {
  49537. this._scene.unregisterAfterRender(this._afterRender);
  49538. this._worker.terminate();
  49539. };
  49540. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49541. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49542. this.onMeshUpdated(mesh);
  49543. };
  49544. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49545. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49546. };
  49547. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49548. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49549. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49550. this.onGeometryUpdated(geometry);
  49551. };
  49552. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49553. this._toRemoveGeometryArray.push(geometry.id);
  49554. };
  49555. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49556. var submeshes = [];
  49557. if (mesh.subMeshes) {
  49558. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49559. var boundingInfo = sm.getBoundingInfo();
  49560. return {
  49561. position: idx,
  49562. verticesStart: sm.verticesStart,
  49563. verticesCount: sm.verticesCount,
  49564. indexStart: sm.indexStart,
  49565. indexCount: sm.indexCount,
  49566. hasMaterial: !!sm.getMaterial(),
  49567. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49568. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49569. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49570. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49571. };
  49572. });
  49573. }
  49574. var geometryId = null;
  49575. if (mesh instanceof BABYLON.Mesh) {
  49576. var geometry = mesh.geometry;
  49577. geometryId = geometry ? geometry.id : null;
  49578. }
  49579. else if (mesh instanceof BABYLON.InstancedMesh) {
  49580. var geometry = mesh.sourceMesh.geometry;
  49581. geometryId = geometry ? geometry.id : null;
  49582. }
  49583. var boundingInfo = mesh.getBoundingInfo();
  49584. return {
  49585. uniqueId: mesh.uniqueId,
  49586. id: mesh.id,
  49587. name: mesh.name,
  49588. geometryId: geometryId,
  49589. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49590. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49591. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49592. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49593. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49594. subMeshes: submeshes,
  49595. checkCollisions: mesh.checkCollisions
  49596. };
  49597. };
  49598. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49599. return {
  49600. id: geometry.id,
  49601. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49602. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49603. indices: new Uint32Array(geometry.getIndices() || []),
  49604. };
  49605. };
  49606. return CollisionCoordinatorWorker;
  49607. }());
  49608. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49609. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49610. function CollisionCoordinatorLegacy() {
  49611. this._scaledPosition = BABYLON.Vector3.Zero();
  49612. this._scaledVelocity = BABYLON.Vector3.Zero();
  49613. this._finalPosition = BABYLON.Vector3.Zero();
  49614. }
  49615. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49616. position.divideToRef(collider._radius, this._scaledPosition);
  49617. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49618. collider.collidedMesh = null;
  49619. collider._retry = 0;
  49620. collider._initialVelocity = this._scaledVelocity;
  49621. collider._initialPosition = this._scaledPosition;
  49622. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  49623. this._finalPosition.multiplyInPlace(collider._radius);
  49624. //run the callback
  49625. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  49626. };
  49627. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  49628. this._scene = scene;
  49629. };
  49630. CollisionCoordinatorLegacy.prototype.destroy = function () {
  49631. //Legacy need no destruction method.
  49632. };
  49633. //No update in legacy mode
  49634. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  49635. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  49636. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  49637. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  49638. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  49639. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  49640. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  49641. if (excludedMesh === void 0) { excludedMesh = null; }
  49642. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  49643. if (collider._retry >= maximumRetry) {
  49644. finalPosition.copyFrom(position);
  49645. return;
  49646. }
  49647. // Check if this is a mesh else camera or -1
  49648. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  49649. collider._initialize(position, velocity, closeDistance);
  49650. // Check all meshes
  49651. for (var index = 0; index < this._scene.meshes.length; index++) {
  49652. var mesh = this._scene.meshes[index];
  49653. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  49654. mesh._checkCollision(collider);
  49655. }
  49656. }
  49657. if (!collider.collisionFound) {
  49658. position.addToRef(velocity, finalPosition);
  49659. return;
  49660. }
  49661. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  49662. collider._getResponse(position, velocity);
  49663. }
  49664. if (velocity.length() <= closeDistance) {
  49665. finalPosition.copyFrom(position);
  49666. return;
  49667. }
  49668. collider._retry++;
  49669. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  49670. };
  49671. return CollisionCoordinatorLegacy;
  49672. }());
  49673. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  49674. })(BABYLON || (BABYLON = {}));
  49675. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  49676. var BABYLON;
  49677. (function (BABYLON) {
  49678. /**
  49679. * A particle represents one of the element emitted by a particle system.
  49680. * This is mainly define by its coordinates, direction, velocity and age.
  49681. */
  49682. var Particle = /** @class */ (function () {
  49683. /**
  49684. * Creates a new instance of @see Particle
  49685. * @param particleSystem the particle system the particle belongs to
  49686. */
  49687. function Particle(particleSystem) {
  49688. this.particleSystem = particleSystem;
  49689. /**
  49690. * The world position of the particle in the scene.
  49691. */
  49692. this.position = BABYLON.Vector3.Zero();
  49693. /**
  49694. * The world direction of the particle in the scene.
  49695. */
  49696. this.direction = BABYLON.Vector3.Zero();
  49697. /**
  49698. * The color of the particle.
  49699. */
  49700. this.color = new BABYLON.Color4(0, 0, 0, 0);
  49701. /**
  49702. * The color change of the particle per step.
  49703. */
  49704. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  49705. /**
  49706. * Defines how long will the life of the particle be.
  49707. */
  49708. this.lifeTime = 1.0;
  49709. /**
  49710. * The current age of the particle.
  49711. */
  49712. this.age = 0;
  49713. /**
  49714. * The current size of the particle.
  49715. */
  49716. this.size = 0;
  49717. /**
  49718. * The current angle of the particle.
  49719. */
  49720. this.angle = 0;
  49721. /**
  49722. * Defines how fast is the angle changing.
  49723. */
  49724. this.angularSpeed = 0;
  49725. /**
  49726. * Defines the cell index used by the particle to be rendered from a sprite.
  49727. */
  49728. this.cellIndex = 0;
  49729. this._currentFrameCounter = 0;
  49730. if (!this.particleSystem.isAnimationSheetEnabled) {
  49731. return;
  49732. }
  49733. this.cellIndex = this.particleSystem.startSpriteCellID;
  49734. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  49735. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  49736. }
  49737. else {
  49738. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  49739. }
  49740. }
  49741. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  49742. // (ageOffset / scaledUpdateSpeed) / available cells
  49743. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  49744. this._currentFrameCounter += scaledUpdateSpeed;
  49745. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  49746. this._currentFrameCounter = 0;
  49747. this.cellIndex++;
  49748. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49749. this.cellIndex = this.particleSystem.endSpriteCellID;
  49750. }
  49751. }
  49752. };
  49753. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  49754. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  49755. this.cellIndex++;
  49756. this._currentFrameCounter = 0;
  49757. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49758. if (this.particleSystem.spriteCellLoop) {
  49759. this.cellIndex = this.particleSystem.startSpriteCellID;
  49760. }
  49761. else {
  49762. this.cellIndex = this.particleSystem.endSpriteCellID;
  49763. }
  49764. }
  49765. }
  49766. else {
  49767. this._currentFrameCounter++;
  49768. }
  49769. };
  49770. /**
  49771. * Copy the properties of particle to another one.
  49772. * @param other the particle to copy the information to.
  49773. */
  49774. Particle.prototype.copyTo = function (other) {
  49775. other.position.copyFrom(this.position);
  49776. other.direction.copyFrom(this.direction);
  49777. other.color.copyFrom(this.color);
  49778. other.colorStep.copyFrom(this.colorStep);
  49779. other.lifeTime = this.lifeTime;
  49780. other.age = this.age;
  49781. other.size = this.size;
  49782. other.angle = this.angle;
  49783. other.angularSpeed = this.angularSpeed;
  49784. other.particleSystem = this.particleSystem;
  49785. other.cellIndex = this.cellIndex;
  49786. };
  49787. return Particle;
  49788. }());
  49789. BABYLON.Particle = Particle;
  49790. })(BABYLON || (BABYLON = {}));
  49791. //# sourceMappingURL=babylon.particle.js.map
  49792. var BABYLON;
  49793. (function (BABYLON) {
  49794. /**
  49795. * This represents a particle system in Babylon.
  49796. * 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.
  49797. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  49798. * @example https://doc.babylonjs.com/babylon101/particles
  49799. */
  49800. var ParticleSystem = /** @class */ (function () {
  49801. /**
  49802. * Instantiates a particle system.
  49803. * 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.
  49804. * @param name The name of the particle system
  49805. * @param capacity The max number of particles alive at the same time
  49806. * @param scene The scene the particle system belongs to
  49807. * @param customEffect a custom effect used to change the way particles are rendered by default
  49808. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  49809. * @param epsilon Offset used to render the particles
  49810. */
  49811. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  49812. if (customEffect === void 0) { customEffect = null; }
  49813. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  49814. if (epsilon === void 0) { epsilon = 0.01; }
  49815. var _this = this;
  49816. /**
  49817. * List of animations used by the particle system.
  49818. */
  49819. this.animations = [];
  49820. /**
  49821. * The rendering group used by the Particle system to chose when to render.
  49822. */
  49823. this.renderingGroupId = 0;
  49824. /**
  49825. * The emitter represents the Mesh or position we are attaching the particle system to.
  49826. */
  49827. this.emitter = null;
  49828. /**
  49829. * The density of particles, the rate of particle flow
  49830. */
  49831. this.emitRate = 10;
  49832. /**
  49833. * If you want to launch only a few particles at once, that can be done, as well.
  49834. */
  49835. this.manualEmitCount = -1;
  49836. /**
  49837. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  49838. */
  49839. this.updateSpeed = 0.01;
  49840. /**
  49841. * The amount of time the particle system is running (depends of the overall speed above).
  49842. */
  49843. this.targetStopDuration = 0;
  49844. /**
  49845. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  49846. */
  49847. this.disposeOnStop = false;
  49848. /**
  49849. * Minimum power of emitting particles.
  49850. */
  49851. this.minEmitPower = 1;
  49852. /**
  49853. * Maximum power of emitting particles.
  49854. */
  49855. this.maxEmitPower = 1;
  49856. /**
  49857. * Minimum life time of emitting particles.
  49858. */
  49859. this.minLifeTime = 1;
  49860. /**
  49861. * Maximum life time of emitting particles.
  49862. */
  49863. this.maxLifeTime = 1;
  49864. /**
  49865. * Minimum Size of emitting particles.
  49866. */
  49867. this.minSize = 1;
  49868. /**
  49869. * Maximum Size of emitting particles.
  49870. */
  49871. this.maxSize = 1;
  49872. /**
  49873. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  49874. */
  49875. this.minAngularSpeed = 0;
  49876. /**
  49877. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  49878. */
  49879. this.maxAngularSpeed = 0;
  49880. /**
  49881. * The layer mask we are rendering the particles through.
  49882. */
  49883. this.layerMask = 0x0FFFFFFF;
  49884. /**
  49885. * This can help using your own shader to render the particle system.
  49886. * The according effect will be created
  49887. */
  49888. this.customShader = null;
  49889. /**
  49890. * By default particle system starts as soon as they are created. This prevents the
  49891. * automatic start to happen and let you decide when to start emitting particles.
  49892. */
  49893. this.preventAutoStart = false;
  49894. /**
  49895. * Callback triggered when the particle animation is ending.
  49896. */
  49897. this.onAnimationEnd = null;
  49898. /**
  49899. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  49900. */
  49901. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  49902. /**
  49903. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  49904. * to override the particles.
  49905. */
  49906. this.forceDepthWrite = false;
  49907. /**
  49908. * You can use gravity if you want to give an orientation to your particles.
  49909. */
  49910. this.gravity = BABYLON.Vector3.Zero();
  49911. /**
  49912. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49913. */
  49914. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  49915. /**
  49916. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49917. */
  49918. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  49919. /**
  49920. * 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.
  49921. */
  49922. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  49923. /**
  49924. * 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.
  49925. */
  49926. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49927. /**
  49928. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  49929. */
  49930. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49931. /**
  49932. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  49933. */
  49934. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49935. /**
  49936. * Color the particle will have at the end of its lifetime.
  49937. */
  49938. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  49939. /**
  49940. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  49941. */
  49942. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49943. /**
  49944. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  49945. */
  49946. this.spriteCellLoop = true;
  49947. /**
  49948. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  49949. */
  49950. this.spriteCellChangeSpeed = 0;
  49951. /**
  49952. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  49953. */
  49954. this.startSpriteCellID = 0;
  49955. /**
  49956. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  49957. */
  49958. this.endSpriteCellID = 0;
  49959. /**
  49960. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  49961. */
  49962. this.spriteCellWidth = 0;
  49963. /**
  49964. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  49965. */
  49966. this.spriteCellHeight = 0;
  49967. /**
  49968. * An event triggered when the system is disposed.
  49969. */
  49970. this.onDisposeObservable = new BABYLON.Observable();
  49971. this._particles = new Array();
  49972. this._stockParticles = new Array();
  49973. this._newPartsExcess = 0;
  49974. this._vertexBuffers = {};
  49975. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  49976. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  49977. this._scaledDirection = BABYLON.Vector3.Zero();
  49978. this._scaledGravity = BABYLON.Vector3.Zero();
  49979. this._currentRenderId = -1;
  49980. this._started = false;
  49981. this._stopped = false;
  49982. this._actualFrame = 0;
  49983. this._vertexBufferSize = 11;
  49984. this._appendParticleVertexes = null;
  49985. this.id = name;
  49986. this.name = name;
  49987. this._capacity = capacity;
  49988. this._epsilon = epsilon;
  49989. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  49990. if (isAnimationSheetEnabled) {
  49991. this._vertexBufferSize = 12;
  49992. }
  49993. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49994. this._customEffect = customEffect;
  49995. scene.particleSystems.push(this);
  49996. this._createIndexBuffer();
  49997. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  49998. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  49999. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50000. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50001. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50002. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50003. if (this._isAnimationSheetEnabled) {
  50004. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50005. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50006. }
  50007. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50008. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50009. this._vertexBuffers["options"] = options;
  50010. // Default behaviors
  50011. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  50012. this.updateFunction = function (particles) {
  50013. for (var index = 0; index < particles.length; index++) {
  50014. var particle = particles[index];
  50015. particle.age += _this._scaledUpdateSpeed;
  50016. if (particle.age >= particle.lifeTime) {
  50017. _this.recycleParticle(particle);
  50018. index--;
  50019. continue;
  50020. }
  50021. else {
  50022. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50023. particle.color.addInPlace(_this._scaledColorStep);
  50024. if (particle.color.a < 0)
  50025. particle.color.a = 0;
  50026. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50027. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50028. particle.position.addInPlace(_this._scaledDirection);
  50029. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50030. particle.direction.addInPlace(_this._scaledGravity);
  50031. if (_this._isAnimationSheetEnabled) {
  50032. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50033. }
  50034. }
  50035. }
  50036. };
  50037. }
  50038. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50039. /**
  50040. * Sets a callback that will be triggered when the system is disposed.
  50041. */
  50042. set: function (callback) {
  50043. if (this._onDisposeObserver) {
  50044. this.onDisposeObservable.remove(this._onDisposeObserver);
  50045. }
  50046. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50047. },
  50048. enumerable: true,
  50049. configurable: true
  50050. });
  50051. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50052. /**
  50053. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50054. */
  50055. get: function () {
  50056. return this._isAnimationSheetEnabled;
  50057. },
  50058. enumerable: true,
  50059. configurable: true
  50060. });
  50061. ParticleSystem.prototype._createIndexBuffer = function () {
  50062. var indices = [];
  50063. var index = 0;
  50064. for (var count = 0; count < this._capacity; count++) {
  50065. indices.push(index);
  50066. indices.push(index + 1);
  50067. indices.push(index + 2);
  50068. indices.push(index);
  50069. indices.push(index + 2);
  50070. indices.push(index + 3);
  50071. index += 4;
  50072. }
  50073. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50074. };
  50075. /**
  50076. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50077. * Its lifetime will start back at 0.
  50078. * @param particle The particle to recycle
  50079. */
  50080. ParticleSystem.prototype.recycleParticle = function (particle) {
  50081. var lastParticle = this._particles.pop();
  50082. if (lastParticle !== particle) {
  50083. lastParticle.copyTo(particle);
  50084. this._stockParticles.push(lastParticle);
  50085. }
  50086. };
  50087. /**
  50088. * Gets the maximum number of particles active at the same time.
  50089. * @returns The max number of active particles.
  50090. */
  50091. ParticleSystem.prototype.getCapacity = function () {
  50092. return this._capacity;
  50093. };
  50094. /**
  50095. * Gets Wether there are still active particles in the system.
  50096. * @returns True if it is alive, otherwise false.
  50097. */
  50098. ParticleSystem.prototype.isAlive = function () {
  50099. return this._alive;
  50100. };
  50101. /**
  50102. * Gets Wether the system has been started.
  50103. * @returns True if it has been started, otherwise false.
  50104. */
  50105. ParticleSystem.prototype.isStarted = function () {
  50106. return this._started;
  50107. };
  50108. /**
  50109. * Starts the particle system and begins to emit.
  50110. */
  50111. ParticleSystem.prototype.start = function () {
  50112. this._started = true;
  50113. this._stopped = false;
  50114. this._actualFrame = 0;
  50115. };
  50116. /**
  50117. * Stops the particle system.
  50118. */
  50119. ParticleSystem.prototype.stop = function () {
  50120. this._stopped = true;
  50121. };
  50122. /**
  50123. * @ignore (for internal use only)
  50124. */
  50125. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50126. var offset = index * this._vertexBufferSize;
  50127. this._vertexData[offset] = particle.position.x;
  50128. this._vertexData[offset + 1] = particle.position.y;
  50129. this._vertexData[offset + 2] = particle.position.z;
  50130. this._vertexData[offset + 3] = particle.color.r;
  50131. this._vertexData[offset + 4] = particle.color.g;
  50132. this._vertexData[offset + 5] = particle.color.b;
  50133. this._vertexData[offset + 6] = particle.color.a;
  50134. this._vertexData[offset + 7] = particle.angle;
  50135. this._vertexData[offset + 8] = particle.size;
  50136. this._vertexData[offset + 9] = offsetX;
  50137. this._vertexData[offset + 10] = offsetY;
  50138. };
  50139. /**
  50140. * @ignore (for internal use only)
  50141. */
  50142. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50143. if (offsetX === 0)
  50144. offsetX = this._epsilon;
  50145. else if (offsetX === 1)
  50146. offsetX = 1 - this._epsilon;
  50147. if (offsetY === 0)
  50148. offsetY = this._epsilon;
  50149. else if (offsetY === 1)
  50150. offsetY = 1 - this._epsilon;
  50151. var offset = index * this._vertexBufferSize;
  50152. this._vertexData[offset] = particle.position.x;
  50153. this._vertexData[offset + 1] = particle.position.y;
  50154. this._vertexData[offset + 2] = particle.position.z;
  50155. this._vertexData[offset + 3] = particle.color.r;
  50156. this._vertexData[offset + 4] = particle.color.g;
  50157. this._vertexData[offset + 5] = particle.color.b;
  50158. this._vertexData[offset + 6] = particle.color.a;
  50159. this._vertexData[offset + 7] = particle.angle;
  50160. this._vertexData[offset + 8] = particle.size;
  50161. this._vertexData[offset + 9] = offsetX;
  50162. this._vertexData[offset + 10] = offsetY;
  50163. this._vertexData[offset + 11] = particle.cellIndex;
  50164. };
  50165. ParticleSystem.prototype._update = function (newParticles) {
  50166. // Update current
  50167. this._alive = this._particles.length > 0;
  50168. this.updateFunction(this._particles);
  50169. // Add new ones
  50170. var worldMatrix;
  50171. if (this.emitter.position) {
  50172. var emitterMesh = this.emitter;
  50173. worldMatrix = emitterMesh.getWorldMatrix();
  50174. }
  50175. else {
  50176. var emitterPosition = this.emitter;
  50177. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50178. }
  50179. var particle;
  50180. for (var index = 0; index < newParticles; index++) {
  50181. if (this._particles.length === this._capacity) {
  50182. break;
  50183. }
  50184. if (this._stockParticles.length !== 0) {
  50185. particle = this._stockParticles.pop();
  50186. particle.age = 0;
  50187. particle.cellIndex = this.startSpriteCellID;
  50188. }
  50189. else {
  50190. particle = new BABYLON.Particle(this);
  50191. }
  50192. this._particles.push(particle);
  50193. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50194. if (this.startPositionFunction) {
  50195. this.startPositionFunction(worldMatrix, particle.position, particle);
  50196. }
  50197. else {
  50198. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50199. }
  50200. if (this.startDirectionFunction) {
  50201. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50202. }
  50203. else {
  50204. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50205. }
  50206. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50207. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50208. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50209. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50210. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50211. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50212. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50213. }
  50214. };
  50215. ParticleSystem.prototype._getEffect = function () {
  50216. if (this._customEffect) {
  50217. return this._customEffect;
  50218. }
  50219. ;
  50220. var defines = [];
  50221. if (this._scene.clipPlane) {
  50222. defines.push("#define CLIPPLANE");
  50223. }
  50224. if (this._isAnimationSheetEnabled) {
  50225. defines.push("#define ANIMATESHEET");
  50226. }
  50227. // Effect
  50228. var join = defines.join("\n");
  50229. if (this._cachedDefines !== join) {
  50230. this._cachedDefines = join;
  50231. var attributesNamesOrOptions;
  50232. var effectCreationOption;
  50233. if (this._isAnimationSheetEnabled) {
  50234. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50235. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50236. }
  50237. else {
  50238. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50239. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50240. }
  50241. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50242. }
  50243. return this._effect;
  50244. };
  50245. /**
  50246. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50247. */
  50248. ParticleSystem.prototype.animate = function () {
  50249. if (!this._started)
  50250. return;
  50251. var effect = this._getEffect();
  50252. // Check
  50253. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50254. return;
  50255. if (this._currentRenderId === this._scene.getRenderId()) {
  50256. return;
  50257. }
  50258. this._currentRenderId = this._scene.getRenderId();
  50259. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50260. // determine the number of particles we need to create
  50261. var newParticles;
  50262. if (this.manualEmitCount > -1) {
  50263. newParticles = this.manualEmitCount;
  50264. this._newPartsExcess = 0;
  50265. this.manualEmitCount = 0;
  50266. }
  50267. else {
  50268. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50269. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50270. }
  50271. if (this._newPartsExcess > 1.0) {
  50272. newParticles += this._newPartsExcess >> 0;
  50273. this._newPartsExcess -= this._newPartsExcess >> 0;
  50274. }
  50275. this._alive = false;
  50276. if (!this._stopped) {
  50277. this._actualFrame += this._scaledUpdateSpeed;
  50278. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50279. this.stop();
  50280. }
  50281. else {
  50282. newParticles = 0;
  50283. }
  50284. this._update(newParticles);
  50285. // Stopped?
  50286. if (this._stopped) {
  50287. if (!this._alive) {
  50288. this._started = false;
  50289. if (this.onAnimationEnd) {
  50290. this.onAnimationEnd();
  50291. }
  50292. if (this.disposeOnStop) {
  50293. this._scene._toBeDisposed.push(this);
  50294. }
  50295. }
  50296. }
  50297. // Animation sheet
  50298. if (this._isAnimationSheetEnabled) {
  50299. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50300. }
  50301. else {
  50302. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50303. }
  50304. // Update VBO
  50305. var offset = 0;
  50306. for (var index = 0; index < this._particles.length; index++) {
  50307. var particle = this._particles[index];
  50308. this._appendParticleVertexes(offset, particle);
  50309. offset += 4;
  50310. }
  50311. if (this._vertexBuffer) {
  50312. this._vertexBuffer.update(this._vertexData);
  50313. }
  50314. };
  50315. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50316. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50317. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50318. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50319. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50320. };
  50321. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50322. this._appendParticleVertex(offset++, particle, 0, 0);
  50323. this._appendParticleVertex(offset++, particle, 1, 0);
  50324. this._appendParticleVertex(offset++, particle, 1, 1);
  50325. this._appendParticleVertex(offset++, particle, 0, 1);
  50326. };
  50327. /**
  50328. * Rebuilds the particle system.
  50329. */
  50330. ParticleSystem.prototype.rebuild = function () {
  50331. this._createIndexBuffer();
  50332. if (this._vertexBuffer) {
  50333. this._vertexBuffer._rebuild();
  50334. }
  50335. };
  50336. /**
  50337. * Renders the particle system in its current state.
  50338. * @returns the current number of particles.
  50339. */
  50340. ParticleSystem.prototype.render = function () {
  50341. var effect = this._getEffect();
  50342. // Check
  50343. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  50344. return 0;
  50345. var engine = this._scene.getEngine();
  50346. // Render
  50347. engine.enableEffect(effect);
  50348. engine.setState(false);
  50349. var viewMatrix = this._scene.getViewMatrix();
  50350. effect.setTexture("diffuseSampler", this.particleTexture);
  50351. effect.setMatrix("view", viewMatrix);
  50352. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50353. if (this._isAnimationSheetEnabled) {
  50354. var baseSize = this.particleTexture.getBaseSize();
  50355. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50356. }
  50357. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50358. if (this._scene.clipPlane) {
  50359. var clipPlane = this._scene.clipPlane;
  50360. var invView = viewMatrix.clone();
  50361. invView.invert();
  50362. effect.setMatrix("invView", invView);
  50363. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50364. }
  50365. // VBOs
  50366. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50367. // Draw order
  50368. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50369. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50370. }
  50371. else {
  50372. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50373. }
  50374. if (this.forceDepthWrite) {
  50375. engine.setDepthWrite(true);
  50376. }
  50377. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50378. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50379. return this._particles.length;
  50380. };
  50381. /**
  50382. * Disposes the particle system and free the associated resources.
  50383. */
  50384. ParticleSystem.prototype.dispose = function () {
  50385. if (this._vertexBuffer) {
  50386. this._vertexBuffer.dispose();
  50387. this._vertexBuffer = null;
  50388. }
  50389. if (this._indexBuffer) {
  50390. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50391. this._indexBuffer = null;
  50392. }
  50393. if (this.particleTexture) {
  50394. this.particleTexture.dispose();
  50395. this.particleTexture = null;
  50396. }
  50397. // Remove from scene
  50398. var index = this._scene.particleSystems.indexOf(this);
  50399. if (index > -1) {
  50400. this._scene.particleSystems.splice(index, 1);
  50401. }
  50402. // Callback
  50403. this.onDisposeObservable.notifyObservers(this);
  50404. this.onDisposeObservable.clear();
  50405. };
  50406. /**
  50407. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50408. * @param radius The radius of the sphere to emit from
  50409. * @returns the emitter
  50410. */
  50411. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50412. if (radius === void 0) { radius = 1; }
  50413. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50414. this.particleEmitterType = particleEmitter;
  50415. return particleEmitter;
  50416. };
  50417. /**
  50418. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50419. * @param radius The radius of the sphere to emit from
  50420. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50421. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50422. * @returns the emitter
  50423. */
  50424. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50425. if (radius === void 0) { radius = 1; }
  50426. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50427. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50428. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50429. this.particleEmitterType = particleEmitter;
  50430. return particleEmitter;
  50431. };
  50432. /**
  50433. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50434. * @param radius The radius of the cone to emit from
  50435. * @param angle The base angle of the cone
  50436. * @returns the emitter
  50437. */
  50438. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50439. if (radius === void 0) { radius = 1; }
  50440. if (angle === void 0) { angle = Math.PI / 4; }
  50441. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50442. this.particleEmitterType = particleEmitter;
  50443. return particleEmitter;
  50444. };
  50445. // 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.
  50446. /**
  50447. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50448. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50449. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50450. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50451. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50452. * @returns the emitter
  50453. */
  50454. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50455. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  50456. this.direction1 = direction1;
  50457. this.direction2 = direction2;
  50458. this.minEmitBox = minEmitBox;
  50459. this.maxEmitBox = maxEmitBox;
  50460. this.particleEmitterType = particleEmitter;
  50461. return particleEmitter;
  50462. };
  50463. /**
  50464. * Clones the particle system.
  50465. * @param name The name of the cloned object
  50466. * @param newEmitter The new emitter to use
  50467. * @returns the cloned particle system
  50468. */
  50469. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50470. var custom = null;
  50471. var program = null;
  50472. if (this.customShader != null) {
  50473. program = this.customShader;
  50474. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50475. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50476. }
  50477. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50478. result.customShader = program;
  50479. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50480. if (newEmitter === undefined) {
  50481. newEmitter = this.emitter;
  50482. }
  50483. result.emitter = newEmitter;
  50484. if (this.particleTexture) {
  50485. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50486. }
  50487. if (!this.preventAutoStart) {
  50488. result.start();
  50489. }
  50490. return result;
  50491. };
  50492. /**
  50493. * Serializes the particle system to a JSON object.
  50494. * @returns the JSON object
  50495. */
  50496. ParticleSystem.prototype.serialize = function () {
  50497. var serializationObject = {};
  50498. serializationObject.name = this.name;
  50499. serializationObject.id = this.id;
  50500. // Emitter
  50501. if (this.emitter.position) {
  50502. var emitterMesh = this.emitter;
  50503. serializationObject.emitterId = emitterMesh.id;
  50504. }
  50505. else {
  50506. var emitterPosition = this.emitter;
  50507. serializationObject.emitter = emitterPosition.asArray();
  50508. }
  50509. serializationObject.capacity = this.getCapacity();
  50510. if (this.particleTexture) {
  50511. serializationObject.textureName = this.particleTexture.name;
  50512. }
  50513. // Animations
  50514. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50515. // Particle system
  50516. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50517. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50518. serializationObject.minSize = this.minSize;
  50519. serializationObject.maxSize = this.maxSize;
  50520. serializationObject.minEmitPower = this.minEmitPower;
  50521. serializationObject.maxEmitPower = this.maxEmitPower;
  50522. serializationObject.minLifeTime = this.minLifeTime;
  50523. serializationObject.maxLifeTime = this.maxLifeTime;
  50524. serializationObject.emitRate = this.emitRate;
  50525. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50526. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50527. serializationObject.gravity = this.gravity.asArray();
  50528. serializationObject.direction1 = this.direction1.asArray();
  50529. serializationObject.direction2 = this.direction2.asArray();
  50530. serializationObject.color1 = this.color1.asArray();
  50531. serializationObject.color2 = this.color2.asArray();
  50532. serializationObject.colorDead = this.colorDead.asArray();
  50533. serializationObject.updateSpeed = this.updateSpeed;
  50534. serializationObject.targetStopDuration = this.targetStopDuration;
  50535. serializationObject.textureMask = this.textureMask.asArray();
  50536. serializationObject.blendMode = this.blendMode;
  50537. serializationObject.customShader = this.customShader;
  50538. serializationObject.preventAutoStart = this.preventAutoStart;
  50539. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50540. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50541. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50542. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50543. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50544. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50545. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50546. return serializationObject;
  50547. };
  50548. /**
  50549. * Parses a JSON object to create a particle system.
  50550. * @param parsedParticleSystem The JSON object to parse
  50551. * @param scene The scene to create the particle system in
  50552. * @param rootUrl The root url to use to load external dependencies like texture
  50553. * @returns the Parsed particle system
  50554. */
  50555. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50556. var name = parsedParticleSystem.name;
  50557. var custom = null;
  50558. var program = null;
  50559. if (parsedParticleSystem.customShader) {
  50560. program = parsedParticleSystem.customShader;
  50561. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50562. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50563. }
  50564. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50565. particleSystem.customShader = program;
  50566. if (parsedParticleSystem.id) {
  50567. particleSystem.id = parsedParticleSystem.id;
  50568. }
  50569. // Auto start
  50570. if (parsedParticleSystem.preventAutoStart) {
  50571. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50572. }
  50573. // Texture
  50574. if (parsedParticleSystem.textureName) {
  50575. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50576. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50577. }
  50578. // Emitter
  50579. if (parsedParticleSystem.emitterId) {
  50580. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50581. }
  50582. else {
  50583. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50584. }
  50585. // Animations
  50586. if (parsedParticleSystem.animations) {
  50587. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50588. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50589. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50590. }
  50591. }
  50592. if (parsedParticleSystem.autoAnimate) {
  50593. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50594. }
  50595. // Particle system
  50596. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50597. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50598. particleSystem.minSize = parsedParticleSystem.minSize;
  50599. particleSystem.maxSize = parsedParticleSystem.maxSize;
  50600. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  50601. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  50602. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  50603. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  50604. particleSystem.emitRate = parsedParticleSystem.emitRate;
  50605. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  50606. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  50607. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  50608. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  50609. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  50610. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  50611. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  50612. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  50613. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  50614. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  50615. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  50616. particleSystem.blendMode = parsedParticleSystem.blendMode;
  50617. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  50618. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  50619. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  50620. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  50621. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  50622. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  50623. if (!particleSystem.preventAutoStart) {
  50624. particleSystem.start();
  50625. }
  50626. return particleSystem;
  50627. };
  50628. /**
  50629. * Source color is added to the destination color without alpha affecting the result.
  50630. */
  50631. ParticleSystem.BLENDMODE_ONEONE = 0;
  50632. /**
  50633. * Blend current color and particle color using particle’s alpha.
  50634. */
  50635. ParticleSystem.BLENDMODE_STANDARD = 1;
  50636. return ParticleSystem;
  50637. }());
  50638. BABYLON.ParticleSystem = ParticleSystem;
  50639. })(BABYLON || (BABYLON = {}));
  50640. //# sourceMappingURL=babylon.particleSystem.js.map
  50641. var BABYLON;
  50642. (function (BABYLON) {
  50643. /**
  50644. * Particle emitter emitting particles from the inside of a box.
  50645. * It emits the particles randomly between 2 given directions.
  50646. */
  50647. var BoxParticleEmitter = /** @class */ (function () {
  50648. // to be updated like the rest of emitters when breaking changes.
  50649. // all property should be come public variables and passed through constructor.
  50650. /**
  50651. * Creates a new instance of @see BoxParticleEmitter
  50652. * @param _particleSystem the particle system associated with the emitter
  50653. */
  50654. function BoxParticleEmitter(_particleSystem) {
  50655. this._particleSystem = _particleSystem;
  50656. }
  50657. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  50658. /**
  50659. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50660. */
  50661. get: function () {
  50662. return this._particleSystem.direction1;
  50663. },
  50664. /**
  50665. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50666. */
  50667. set: function (value) {
  50668. this._particleSystem.direction1 = value;
  50669. },
  50670. enumerable: true,
  50671. configurable: true
  50672. });
  50673. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  50674. /**
  50675. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50676. */
  50677. get: function () {
  50678. return this._particleSystem.direction2;
  50679. },
  50680. /**
  50681. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50682. */
  50683. set: function (value) {
  50684. this._particleSystem.direction2 = value;
  50685. },
  50686. enumerable: true,
  50687. configurable: true
  50688. });
  50689. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  50690. /**
  50691. * 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.
  50692. */
  50693. get: function () {
  50694. return this._particleSystem.minEmitBox;
  50695. },
  50696. /**
  50697. * 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.
  50698. */
  50699. set: function (value) {
  50700. this._particleSystem.minEmitBox = value;
  50701. },
  50702. enumerable: true,
  50703. configurable: true
  50704. });
  50705. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  50706. /**
  50707. * 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.
  50708. */
  50709. get: function () {
  50710. return this._particleSystem.maxEmitBox;
  50711. },
  50712. /**
  50713. * 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.
  50714. */
  50715. set: function (value) {
  50716. this._particleSystem.maxEmitBox = value;
  50717. },
  50718. enumerable: true,
  50719. configurable: true
  50720. });
  50721. /**
  50722. * Called by the particle System when the direction is computed for the created particle.
  50723. * @param emitPower is the power of the particle (speed)
  50724. * @param worldMatrix is the world matrix of the particle system
  50725. * @param directionToUpdate is the direction vector to update with the result
  50726. * @param particle is the particle we are computed the direction for
  50727. */
  50728. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50729. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  50730. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  50731. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  50732. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  50733. };
  50734. /**
  50735. * Called by the particle System when the position is computed for the created particle.
  50736. * @param worldMatrix is the world matrix of the particle system
  50737. * @param positionToUpdate is the position vector to update with the result
  50738. * @param particle is the particle we are computed the position for
  50739. */
  50740. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50741. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  50742. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  50743. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  50744. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50745. };
  50746. /**
  50747. * Clones the current emitter and returns a copy of it
  50748. * @returns the new emitter
  50749. */
  50750. BoxParticleEmitter.prototype.clone = function () {
  50751. var newOne = new BoxParticleEmitter(this._particleSystem);
  50752. BABYLON.Tools.DeepCopy(this, newOne);
  50753. return newOne;
  50754. };
  50755. return BoxParticleEmitter;
  50756. }());
  50757. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  50758. })(BABYLON || (BABYLON = {}));
  50759. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  50760. var BABYLON;
  50761. (function (BABYLON) {
  50762. /**
  50763. * Particle emitter emitting particles from the inside of a cone.
  50764. * It emits the particles alongside the cone volume from the base to the particle.
  50765. * The emission direction might be randomized.
  50766. */
  50767. var ConeParticleEmitter = /** @class */ (function () {
  50768. /**
  50769. * Creates a new instance of @see ConeParticleEmitter
  50770. * @param radius the radius of the emission cone
  50771. * @param angles the cone base angle
  50772. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50773. */
  50774. function ConeParticleEmitter(radius,
  50775. /**
  50776. * The radius of the emission cone.
  50777. */
  50778. angle,
  50779. /**
  50780. * The cone base angle.
  50781. */
  50782. directionRandomizer) {
  50783. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50784. this.angle = angle;
  50785. this.directionRandomizer = directionRandomizer;
  50786. this.radius = radius;
  50787. }
  50788. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  50789. /**
  50790. * Gets the radius of the emission cone.
  50791. */
  50792. get: function () {
  50793. return this._radius;
  50794. },
  50795. /**
  50796. * Sets the radius of the emission cone.
  50797. */
  50798. set: function (value) {
  50799. this._radius = value;
  50800. if (this.angle !== 0) {
  50801. this._height = value / Math.tan(this.angle / 2);
  50802. }
  50803. else {
  50804. this._height = 1;
  50805. }
  50806. },
  50807. enumerable: true,
  50808. configurable: true
  50809. });
  50810. /**
  50811. * Called by the particle System when the direction is computed for the created particle.
  50812. * @param emitPower is the power of the particle (speed)
  50813. * @param worldMatrix is the world matrix of the particle system
  50814. * @param directionToUpdate is the direction vector to update with the result
  50815. * @param particle is the particle we are computed the direction for
  50816. */
  50817. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50818. if (this.angle === 0) {
  50819. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  50820. }
  50821. else {
  50822. // measure the direction Vector from the emitter to the particle.
  50823. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50824. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50825. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50826. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50827. direction.x += randX;
  50828. direction.y += randY;
  50829. direction.z += randZ;
  50830. direction.normalize();
  50831. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50832. }
  50833. };
  50834. /**
  50835. * Called by the particle System when the position is computed for the created particle.
  50836. * @param worldMatrix is the world matrix of the particle system
  50837. * @param positionToUpdate is the position vector to update with the result
  50838. * @param particle is the particle we are computed the position for
  50839. */
  50840. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50841. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  50842. var h = BABYLON.Scalar.RandomRange(0, 1);
  50843. // Better distribution in a cone at normal angles.
  50844. h = 1 - h * h;
  50845. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  50846. radius = radius * h / this._height;
  50847. var randX = radius * Math.sin(s);
  50848. var randZ = radius * Math.cos(s);
  50849. var randY = h;
  50850. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50851. };
  50852. /**
  50853. * Clones the current emitter and returns a copy of it
  50854. * @returns the new emitter
  50855. */
  50856. ConeParticleEmitter.prototype.clone = function () {
  50857. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  50858. BABYLON.Tools.DeepCopy(this, newOne);
  50859. return newOne;
  50860. };
  50861. return ConeParticleEmitter;
  50862. }());
  50863. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  50864. })(BABYLON || (BABYLON = {}));
  50865. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  50866. var BABYLON;
  50867. (function (BABYLON) {
  50868. /**
  50869. * Particle emitter emitting particles from the inside of a sphere.
  50870. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  50871. */
  50872. var SphereParticleEmitter = /** @class */ (function () {
  50873. /**
  50874. * Creates a new instance of @see SphereParticleEmitter
  50875. * @param radius the radius of the emission sphere
  50876. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50877. */
  50878. function SphereParticleEmitter(
  50879. /**
  50880. * The radius of the emission sphere.
  50881. */
  50882. radius,
  50883. /**
  50884. * How much to randomize the particle direction [0-1].
  50885. */
  50886. directionRandomizer) {
  50887. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50888. this.radius = radius;
  50889. this.directionRandomizer = directionRandomizer;
  50890. }
  50891. /**
  50892. * Called by the particle System when the direction is computed for the created particle.
  50893. * @param emitPower is the power of the particle (speed)
  50894. * @param worldMatrix is the world matrix of the particle system
  50895. * @param directionToUpdate is the direction vector to update with the result
  50896. * @param particle is the particle we are computed the direction for
  50897. */
  50898. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50899. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50900. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50901. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50902. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50903. direction.x += randX;
  50904. direction.y += randY;
  50905. direction.z += randZ;
  50906. direction.normalize();
  50907. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50908. };
  50909. /**
  50910. * Called by the particle System when the position is computed for the created particle.
  50911. * @param worldMatrix is the world matrix of the particle system
  50912. * @param positionToUpdate is the position vector to update with the result
  50913. * @param particle is the particle we are computed the position for
  50914. */
  50915. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50916. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  50917. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  50918. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  50919. var randY = this.radius * Math.cos(theta);
  50920. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  50921. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50922. };
  50923. /**
  50924. * Clones the current emitter and returns a copy of it
  50925. * @returns the new emitter
  50926. */
  50927. SphereParticleEmitter.prototype.clone = function () {
  50928. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  50929. BABYLON.Tools.DeepCopy(this, newOne);
  50930. return newOne;
  50931. };
  50932. return SphereParticleEmitter;
  50933. }());
  50934. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  50935. /**
  50936. * Particle emitter emitting particles from the inside of a sphere.
  50937. * It emits the particles randomly between two vectors.
  50938. */
  50939. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  50940. __extends(SphereDirectedParticleEmitter, _super);
  50941. /**
  50942. * Creates a new instance of @see SphereDirectedParticleEmitter
  50943. * @param radius the radius of the emission sphere
  50944. * @param direction1 the min limit of the emission direction
  50945. * @param direction2 the max limit of the emission direction
  50946. */
  50947. function SphereDirectedParticleEmitter(radius,
  50948. /**
  50949. * The min limit of the emission direction.
  50950. */
  50951. direction1,
  50952. /**
  50953. * The max limit of the emission direction.
  50954. */
  50955. direction2) {
  50956. var _this = _super.call(this, radius) || this;
  50957. _this.direction1 = direction1;
  50958. _this.direction2 = direction2;
  50959. return _this;
  50960. }
  50961. /**
  50962. * Called by the particle System when the direction is computed for the created particle.
  50963. * @param emitPower is the power of the particle (speed)
  50964. * @param worldMatrix is the world matrix of the particle system
  50965. * @param directionToUpdate is the direction vector to update with the result
  50966. * @param particle is the particle we are computed the direction for
  50967. */
  50968. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50969. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  50970. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  50971. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  50972. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  50973. };
  50974. /**
  50975. * Clones the current emitter and returns a copy of it
  50976. * @returns the new emitter
  50977. */
  50978. SphereDirectedParticleEmitter.prototype.clone = function () {
  50979. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  50980. BABYLON.Tools.DeepCopy(this, newOne);
  50981. return newOne;
  50982. };
  50983. return SphereDirectedParticleEmitter;
  50984. }(SphereParticleEmitter));
  50985. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  50986. })(BABYLON || (BABYLON = {}));
  50987. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  50988. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  50989. var BABYLON;
  50990. (function (BABYLON) {
  50991. /**
  50992. * This represents a GPU particle system in Babylon.
  50993. * This os the fastest particle system in Babylon as it uses the GPU to update the individual particle data.
  50994. */
  50995. var GPUParticleSystem = /** @class */ (function () {
  50996. /**
  50997. * Instantiates a GPU particle system.
  50998. * 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.
  50999. * @param name The name of the particle system
  51000. * @param capacity The max number of particles alive at the same time
  51001. * @param scene The scene the particle system belongs to
  51002. */
  51003. function GPUParticleSystem(name, capacity, scene) {
  51004. /**
  51005. * The emitter represents the Mesh or position we are attaching the particle system to.
  51006. */
  51007. this.emitter = null;
  51008. /**
  51009. * The rendering group used by the Particle system to chose when to render.
  51010. */
  51011. this.renderingGroupId = 0;
  51012. /**
  51013. * The layer mask we are rendering the particles through.
  51014. */
  51015. this.layerMask = 0x0FFFFFFF; // TODO
  51016. this._updateVertexBuffers = {};
  51017. this._renderVertexBuffers = {};
  51018. this._currentRenderId = -1;
  51019. this._started = true;
  51020. /**
  51021. * An event triggered when the system is disposed.
  51022. */
  51023. this.onDisposeObservable = new BABYLON.Observable();
  51024. this.id = name;
  51025. this.name = name;
  51026. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51027. this._capacity = capacity;
  51028. this._engine = this._scene.getEngine();
  51029. this._scene.particleSystems.push(this);
  51030. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  51031. var updateEffectOptions = {
  51032. attributes: ["position", "age", "life", "velocity"],
  51033. uniformsNames: [],
  51034. uniformBuffersNames: [],
  51035. samplers: [],
  51036. defines: "",
  51037. fallbacks: null,
  51038. onCompiled: null,
  51039. onError: null,
  51040. indexParameters: null,
  51041. maxSimultaneousLights: 0,
  51042. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  51043. };
  51044. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  51045. }
  51046. /**
  51047. * Gets Wether the system has been started.
  51048. * @returns True if it has been started, otherwise false.
  51049. */
  51050. GPUParticleSystem.prototype.isStarted = function () {
  51051. return this._started;
  51052. };
  51053. /**
  51054. * Starts the particle system and begins to emit.
  51055. */
  51056. GPUParticleSystem.prototype.start = function () {
  51057. this._started = true;
  51058. };
  51059. /**
  51060. * Stops the particle system.
  51061. */
  51062. GPUParticleSystem.prototype.stop = function () {
  51063. this._started = false;
  51064. };
  51065. /**
  51066. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51067. */
  51068. GPUParticleSystem.prototype.animate = function () {
  51069. // Do nothing
  51070. };
  51071. GPUParticleSystem.prototype._initialize = function () {
  51072. if (this._renderVAO) {
  51073. return;
  51074. }
  51075. var data = new Array();
  51076. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  51077. // position
  51078. data.push(0.0);
  51079. data.push(0.0);
  51080. data.push(0.0);
  51081. var life = 1 + Math.random() * 10; // TODO: var
  51082. data.push(life + 1); // create the particle as a dead one to create a new one at start
  51083. data.push(life);
  51084. // velocity
  51085. data.push(0.0);
  51086. data.push(0.0);
  51087. data.push(0.0);
  51088. }
  51089. // Update VAO
  51090. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  51091. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  51092. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  51093. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  51094. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  51095. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  51096. this._engine.bindArrayBuffer(null);
  51097. // Render VAO
  51098. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  51099. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  51100. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  51101. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  51102. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  51103. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  51104. this._engine.bindArrayBuffer(null);
  51105. // Links
  51106. this._sourceVAO = this._updateVAO;
  51107. this._targetVAO = this._renderVAO;
  51108. this._sourceBuffer = this._updateBuffer;
  51109. this._targetBuffer = this._renderBuffer;
  51110. };
  51111. /**
  51112. * Renders the particle system in its current state.
  51113. * @returns the current number of particles.
  51114. */
  51115. GPUParticleSystem.prototype.render = function () {
  51116. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  51117. return 0;
  51118. }
  51119. // Get everything ready to render
  51120. this._initialize();
  51121. if (this._currentRenderId === this._scene.getRenderId()) {
  51122. return 0;
  51123. }
  51124. this._currentRenderId = this._scene.getRenderId();
  51125. // Enable update effect
  51126. this._engine.enableEffect(this._updateEffect);
  51127. this._engine.setState(false);
  51128. // Bind source VAO
  51129. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  51130. // Update
  51131. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  51132. this._engine.setRasterizerState(false);
  51133. this._engine.beginTransformFeedback();
  51134. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  51135. this._engine.endTransformFeedback();
  51136. this._engine.setRasterizerState(true);
  51137. this._engine.bindTransformFeedbackBuffer(null);
  51138. // Enable render effect
  51139. this._engine.enableEffect(this._renderEffect);
  51140. // Bind source VAO
  51141. this._engine.bindVertexArrayObject(this._targetVAO, null);
  51142. // Render
  51143. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  51144. // Switch VAOs
  51145. var tmpVAO = this._sourceVAO;
  51146. this._sourceVAO = this._targetVAO;
  51147. this._targetVAO = tmpVAO;
  51148. // Switch buffers
  51149. var tmpBuffer = this._sourceBuffer;
  51150. this._sourceBuffer = this._targetBuffer;
  51151. this._targetBuffer = tmpBuffer;
  51152. return 0;
  51153. };
  51154. /**
  51155. * Rebuilds the particle system
  51156. */
  51157. GPUParticleSystem.prototype.rebuild = function () {
  51158. };
  51159. /**
  51160. * Disposes the particle system and free the associated resources.
  51161. */
  51162. GPUParticleSystem.prototype.dispose = function () {
  51163. var index = this._scene.particleSystems.indexOf(this);
  51164. if (index > -1) {
  51165. this._scene.particleSystems.splice(index, 1);
  51166. }
  51167. //TODO: this._dataBuffer.dispose();
  51168. // Callback
  51169. this.onDisposeObservable.notifyObservers(this);
  51170. this.onDisposeObservable.clear();
  51171. };
  51172. //TODO: Clone / Parse / serialize
  51173. /**
  51174. * Clones the particle system.
  51175. * @param name The name of the cloned object
  51176. * @param newEmitter The new emitter to use
  51177. * @returns the cloned particle system
  51178. */
  51179. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  51180. return null;
  51181. };
  51182. /**
  51183. * Serializes the particle system to a JSON object.
  51184. * @returns the JSON object
  51185. */
  51186. GPUParticleSystem.prototype.serialize = function () {
  51187. };
  51188. return GPUParticleSystem;
  51189. }());
  51190. BABYLON.GPUParticleSystem = GPUParticleSystem;
  51191. })(BABYLON || (BABYLON = {}));
  51192. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  51193. var BABYLON;
  51194. (function (BABYLON) {
  51195. /**
  51196. * Represents one particle of a solid particle system.
  51197. * @see SolidParticleSystem
  51198. */
  51199. var SolidParticle = /** @class */ (function () {
  51200. /**
  51201. * Creates a Solid Particle object.
  51202. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51203. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51204. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  51205. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  51206. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  51207. * @param shapeId (integer) is the model shape identifier in the SPS.
  51208. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  51209. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  51210. */
  51211. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51212. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  51213. /**
  51214. * particle global index
  51215. */
  51216. this.idx = 0;
  51217. /**
  51218. * The color of the particle
  51219. */
  51220. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51221. /**
  51222. * The world space position of the particle.
  51223. */
  51224. this.position = BABYLON.Vector3.Zero();
  51225. /**
  51226. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  51227. */
  51228. this.rotation = BABYLON.Vector3.Zero();
  51229. /**
  51230. * The scaling of the particle.
  51231. */
  51232. this.scaling = BABYLON.Vector3.One();
  51233. /**
  51234. * The uvs of the particle.
  51235. */
  51236. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51237. /**
  51238. * The current speed of the particle.
  51239. */
  51240. this.velocity = BABYLON.Vector3.Zero();
  51241. /**
  51242. * The pivot point in the particle local space.
  51243. */
  51244. this.pivot = BABYLON.Vector3.Zero();
  51245. /**
  51246. * Must the particle be translated from its pivot point in its local space ?
  51247. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51248. * Default : false
  51249. */
  51250. this.translateFromPivot = false;
  51251. /**
  51252. * Is the particle active or not ?
  51253. */
  51254. this.alive = true;
  51255. /**
  51256. * Is the particle visible or not ?
  51257. */
  51258. this.isVisible = true;
  51259. /**
  51260. * Index of this particle in the global "positions" array (Internal use)
  51261. */
  51262. this._pos = 0;
  51263. /**
  51264. * Index of this particle in the global "indices" array (Internal use)
  51265. */
  51266. this._ind = 0;
  51267. /**
  51268. * ModelShape id of this particle
  51269. */
  51270. this.shapeId = 0;
  51271. /**
  51272. * Index of the particle in its shape id (Internal use)
  51273. */
  51274. this.idxInShape = 0;
  51275. /**
  51276. * Still set as invisible in order to skip useless computations (Internal use)
  51277. */
  51278. this._stillInvisible = false;
  51279. /**
  51280. * Last computed particle rotation matrix
  51281. */
  51282. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  51283. this.idx = particleIndex;
  51284. this._pos = positionIndex;
  51285. this._ind = indiceIndex;
  51286. this._model = model;
  51287. this.shapeId = shapeId;
  51288. this.idxInShape = idxInShape;
  51289. this._sps = sps;
  51290. if (modelBoundingInfo) {
  51291. this._modelBoundingInfo = modelBoundingInfo;
  51292. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  51293. }
  51294. }
  51295. Object.defineProperty(SolidParticle.prototype, "scale", {
  51296. /**
  51297. * Legacy support, changed scale to scaling
  51298. */
  51299. get: function () {
  51300. return this.scaling;
  51301. },
  51302. /**
  51303. * Legacy support, changed scale to scaling
  51304. */
  51305. set: function (scale) {
  51306. this.scaling = scale;
  51307. },
  51308. enumerable: true,
  51309. configurable: true
  51310. });
  51311. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  51312. /**
  51313. * Legacy support, changed quaternion to rotationQuaternion
  51314. */
  51315. get: function () {
  51316. return this.rotationQuaternion;
  51317. },
  51318. /**
  51319. * Legacy support, changed quaternion to rotationQuaternion
  51320. */
  51321. set: function (q) {
  51322. this.rotationQuaternion = q;
  51323. },
  51324. enumerable: true,
  51325. configurable: true
  51326. });
  51327. /**
  51328. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  51329. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  51330. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  51331. * @returns true if it intersects
  51332. */
  51333. SolidParticle.prototype.intersectsMesh = function (target) {
  51334. if (!this._boundingInfo || !target._boundingInfo) {
  51335. return false;
  51336. }
  51337. if (this._sps._bSphereOnly) {
  51338. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  51339. }
  51340. return this._boundingInfo.intersects(target._boundingInfo, false);
  51341. };
  51342. return SolidParticle;
  51343. }());
  51344. BABYLON.SolidParticle = SolidParticle;
  51345. /**
  51346. * Represents the shape of the model used by one particle of a solid particle system.
  51347. * SPS internal tool, don't use it manually.
  51348. * @see SolidParticleSystem
  51349. */
  51350. var ModelShape = /** @class */ (function () {
  51351. /**
  51352. * 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.
  51353. * SPS internal tool, don't use it manually.
  51354. * @ignore
  51355. */
  51356. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  51357. /**
  51358. * length of the shape in the model indices array (internal use)
  51359. */
  51360. this._indicesLength = 0;
  51361. this.shapeID = id;
  51362. this._shape = shape;
  51363. this._indicesLength = indicesLength;
  51364. this._shapeUV = shapeUV;
  51365. this._positionFunction = posFunction;
  51366. this._vertexFunction = vtxFunction;
  51367. }
  51368. return ModelShape;
  51369. }());
  51370. BABYLON.ModelShape = ModelShape;
  51371. /**
  51372. * Represents a Depth Sorted Particle in the solid particle system.
  51373. * @see SolidParticleSystem
  51374. */
  51375. var DepthSortedParticle = /** @class */ (function () {
  51376. function DepthSortedParticle() {
  51377. /**
  51378. * Index of the particle in the "indices" array
  51379. */
  51380. this.ind = 0;
  51381. /**
  51382. * Length of the particle shape in the "indices" array
  51383. */
  51384. this.indicesLength = 0;
  51385. /**
  51386. * Squared distance from the particle to the camera
  51387. */
  51388. this.sqDistance = 0.0;
  51389. }
  51390. return DepthSortedParticle;
  51391. }());
  51392. BABYLON.DepthSortedParticle = DepthSortedParticle;
  51393. })(BABYLON || (BABYLON = {}));
  51394. //# sourceMappingURL=babylon.solidParticle.js.map
  51395. var BABYLON;
  51396. (function (BABYLON) {
  51397. /**
  51398. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  51399. *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.
  51400. * The SPS is also a particle system. It provides some methods to manage the particles.
  51401. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  51402. *
  51403. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  51404. */
  51405. var SolidParticleSystem = /** @class */ (function () {
  51406. /**
  51407. * Creates a SPS (Solid Particle System) object.
  51408. * @param name (String) is the SPS name, this will be the underlying mesh name.
  51409. * @param scene (Scene) is the scene in which the SPS is added.
  51410. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  51411. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  51412. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  51413. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  51414. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  51415. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  51416. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  51417. */
  51418. function SolidParticleSystem(name, scene, options) {
  51419. /**
  51420. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  51421. * Example : var p = SPS.particles[i];
  51422. */
  51423. this.particles = new Array();
  51424. /**
  51425. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  51426. */
  51427. this.nbParticles = 0;
  51428. /**
  51429. * If the particles must ever face the camera (default false). Useful for planar particles.
  51430. */
  51431. this.billboard = false;
  51432. /**
  51433. * Recompute normals when adding a shape
  51434. */
  51435. this.recomputeNormals = true;
  51436. /**
  51437. * This a counter ofr your own usage. It's not set by any SPS functions.
  51438. */
  51439. this.counter = 0;
  51440. /**
  51441. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  51442. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  51443. */
  51444. this.vars = {};
  51445. /**
  51446. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  51447. */
  51448. this._bSphereOnly = false;
  51449. /**
  51450. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  51451. */
  51452. this._bSphereRadiusFactor = 1.0;
  51453. this._positions = new Array();
  51454. this._indices = new Array();
  51455. this._normals = new Array();
  51456. this._colors = new Array();
  51457. this._uvs = new Array();
  51458. this._index = 0; // indices index
  51459. this._updatable = true;
  51460. this._pickable = false;
  51461. this._isVisibilityBoxLocked = false;
  51462. this._alwaysVisible = false;
  51463. this._depthSort = false;
  51464. this._shapeCounter = 0;
  51465. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  51466. this._color = new BABYLON.Color4(0, 0, 0, 0);
  51467. this._computeParticleColor = true;
  51468. this._computeParticleTexture = true;
  51469. this._computeParticleRotation = true;
  51470. this._computeParticleVertex = false;
  51471. this._computeBoundingBox = false;
  51472. this._depthSortParticles = true;
  51473. this._cam_axisZ = BABYLON.Vector3.Zero();
  51474. this._cam_axisY = BABYLON.Vector3.Zero();
  51475. this._cam_axisX = BABYLON.Vector3.Zero();
  51476. this._axisZ = BABYLON.Axis.Z;
  51477. this._camDir = BABYLON.Vector3.Zero();
  51478. this._camInvertedPosition = BABYLON.Vector3.Zero();
  51479. this._rotMatrix = new BABYLON.Matrix();
  51480. this._invertMatrix = new BABYLON.Matrix();
  51481. this._rotated = BABYLON.Vector3.Zero();
  51482. this._quaternion = new BABYLON.Quaternion();
  51483. this._vertex = BABYLON.Vector3.Zero();
  51484. this._normal = BABYLON.Vector3.Zero();
  51485. this._yaw = 0.0;
  51486. this._pitch = 0.0;
  51487. this._roll = 0.0;
  51488. this._halfroll = 0.0;
  51489. this._halfpitch = 0.0;
  51490. this._halfyaw = 0.0;
  51491. this._sinRoll = 0.0;
  51492. this._cosRoll = 0.0;
  51493. this._sinPitch = 0.0;
  51494. this._cosPitch = 0.0;
  51495. this._sinYaw = 0.0;
  51496. this._cosYaw = 0.0;
  51497. this._mustUnrotateFixedNormals = false;
  51498. this._minimum = BABYLON.Vector3.Zero();
  51499. this._maximum = BABYLON.Vector3.Zero();
  51500. this._minBbox = BABYLON.Vector3.Zero();
  51501. this._maxBbox = BABYLON.Vector3.Zero();
  51502. this._particlesIntersect = false;
  51503. this._depthSortFunction = function (p1, p2) {
  51504. return (p2.sqDistance - p1.sqDistance);
  51505. };
  51506. this._needs32Bits = false;
  51507. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  51508. this.name = name;
  51509. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51510. this._camera = scene.activeCamera;
  51511. this._pickable = options ? options.isPickable : false;
  51512. this._depthSort = options ? options.enableDepthSort : false;
  51513. this._particlesIntersect = options ? options.particleIntersection : false;
  51514. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  51515. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  51516. if (options && options.updatable) {
  51517. this._updatable = options.updatable;
  51518. }
  51519. else {
  51520. this._updatable = true;
  51521. }
  51522. if (this._pickable) {
  51523. this.pickedParticles = [];
  51524. }
  51525. if (this._depthSort) {
  51526. this.depthSortedParticles = [];
  51527. }
  51528. }
  51529. /**
  51530. * Builds the SPS underlying mesh. Returns a standard Mesh.
  51531. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  51532. * @returns the created mesh
  51533. */
  51534. SolidParticleSystem.prototype.buildMesh = function () {
  51535. if (this.nbParticles === 0) {
  51536. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  51537. this.addShape(triangle, 1);
  51538. triangle.dispose();
  51539. }
  51540. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  51541. this._positions32 = new Float32Array(this._positions);
  51542. this._uvs32 = new Float32Array(this._uvs);
  51543. this._colors32 = new Float32Array(this._colors);
  51544. if (this.recomputeNormals) {
  51545. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  51546. }
  51547. this._normals32 = new Float32Array(this._normals);
  51548. this._fixedNormal32 = new Float32Array(this._normals);
  51549. if (this._mustUnrotateFixedNormals) {
  51550. this._unrotateFixedNormals();
  51551. }
  51552. var vertexData = new BABYLON.VertexData();
  51553. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  51554. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  51555. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  51556. if (this._uvs32) {
  51557. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  51558. ;
  51559. }
  51560. if (this._colors32) {
  51561. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  51562. }
  51563. var mesh = new BABYLON.Mesh(this.name, this._scene);
  51564. vertexData.applyToMesh(mesh, this._updatable);
  51565. this.mesh = mesh;
  51566. this.mesh.isPickable = this._pickable;
  51567. // free memory
  51568. if (!this._depthSort) {
  51569. this._indices = null;
  51570. }
  51571. this._positions = null;
  51572. this._normals = null;
  51573. this._uvs = null;
  51574. this._colors = null;
  51575. if (!this._updatable) {
  51576. this.particles.length = 0;
  51577. }
  51578. return mesh;
  51579. };
  51580. /**
  51581. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  51582. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  51583. * Thus the particles generated from `digest()` have their property `position` set yet.
  51584. * @param mesh ( Mesh ) is the mesh to be digested
  51585. * @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
  51586. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  51587. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  51588. * @returns the current SPS
  51589. */
  51590. SolidParticleSystem.prototype.digest = function (mesh, options) {
  51591. var size = (options && options.facetNb) || 1;
  51592. var number = (options && options.number) || 0;
  51593. var delta = (options && options.delta) || 0;
  51594. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51595. var meshInd = mesh.getIndices();
  51596. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51597. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51598. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51599. var f = 0; // facet counter
  51600. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  51601. // compute size from number
  51602. if (number) {
  51603. number = (number > totalFacets) ? totalFacets : number;
  51604. size = Math.round(totalFacets / number);
  51605. delta = 0;
  51606. }
  51607. else {
  51608. size = (size > totalFacets) ? totalFacets : size;
  51609. }
  51610. var facetPos = []; // submesh positions
  51611. var facetInd = []; // submesh indices
  51612. var facetUV = []; // submesh UV
  51613. var facetCol = []; // submesh colors
  51614. var barycenter = BABYLON.Vector3.Zero();
  51615. var sizeO = size;
  51616. while (f < totalFacets) {
  51617. size = sizeO + Math.floor((1 + delta) * Math.random());
  51618. if (f > totalFacets - size) {
  51619. size = totalFacets - f;
  51620. }
  51621. // reset temp arrays
  51622. facetPos.length = 0;
  51623. facetInd.length = 0;
  51624. facetUV.length = 0;
  51625. facetCol.length = 0;
  51626. // iterate over "size" facets
  51627. var fi = 0;
  51628. for (var j = f * 3; j < (f + size) * 3; j++) {
  51629. facetInd.push(fi);
  51630. var i = meshInd[j];
  51631. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  51632. if (meshUV) {
  51633. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  51634. }
  51635. if (meshCol) {
  51636. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  51637. }
  51638. fi++;
  51639. }
  51640. // create a model shape for each single particle
  51641. var idx = this.nbParticles;
  51642. var shape = this._posToShape(facetPos);
  51643. var shapeUV = this._uvsToShapeUV(facetUV);
  51644. // compute the barycenter of the shape
  51645. var v;
  51646. for (v = 0; v < shape.length; v++) {
  51647. barycenter.addInPlace(shape[v]);
  51648. }
  51649. barycenter.scaleInPlace(1 / shape.length);
  51650. // shift the shape from its barycenter to the origin
  51651. for (v = 0; v < shape.length; v++) {
  51652. shape[v].subtractInPlace(barycenter);
  51653. }
  51654. var bInfo;
  51655. if (this._particlesIntersect) {
  51656. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  51657. }
  51658. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  51659. // add the particle in the SPS
  51660. var currentPos = this._positions.length;
  51661. var currentInd = this._indices.length;
  51662. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  51663. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  51664. // initialize the particle position
  51665. this.particles[this.nbParticles].position.addInPlace(barycenter);
  51666. this._index += shape.length;
  51667. idx++;
  51668. this.nbParticles++;
  51669. this._shapeCounter++;
  51670. f += size;
  51671. }
  51672. return this;
  51673. };
  51674. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  51675. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  51676. var index = 0;
  51677. var idx = 0;
  51678. for (var p = 0; p < this.particles.length; p++) {
  51679. this._particle = this.particles[p];
  51680. this._shape = this._particle._model._shape;
  51681. if (this._particle.rotationQuaternion) {
  51682. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51683. }
  51684. else {
  51685. this._yaw = this._particle.rotation.y;
  51686. this._pitch = this._particle.rotation.x;
  51687. this._roll = this._particle.rotation.z;
  51688. this._quaternionRotationYPR();
  51689. }
  51690. this._quaternionToRotationMatrix();
  51691. this._rotMatrix.invertToRef(this._invertMatrix);
  51692. for (var pt = 0; pt < this._shape.length; pt++) {
  51693. idx = index + pt * 3;
  51694. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  51695. this._fixedNormal32[idx] = this._normal.x;
  51696. this._fixedNormal32[idx + 1] = this._normal.y;
  51697. this._fixedNormal32[idx + 2] = this._normal.z;
  51698. }
  51699. index = idx + 3;
  51700. }
  51701. };
  51702. //reset copy
  51703. SolidParticleSystem.prototype._resetCopy = function () {
  51704. this._copy.position.x = 0;
  51705. this._copy.position.y = 0;
  51706. this._copy.position.z = 0;
  51707. this._copy.rotation.x = 0;
  51708. this._copy.rotation.y = 0;
  51709. this._copy.rotation.z = 0;
  51710. this._copy.rotationQuaternion = null;
  51711. this._copy.scaling.x = 1.0;
  51712. this._copy.scaling.y = 1.0;
  51713. this._copy.scaling.z = 1.0;
  51714. this._copy.uvs.x = 0;
  51715. this._copy.uvs.y = 0;
  51716. this._copy.uvs.z = 1.0;
  51717. this._copy.uvs.w = 1.0;
  51718. this._copy.color = null;
  51719. this._copy.translateFromPivot = false;
  51720. };
  51721. // _meshBuilder : inserts the shape model in the global SPS mesh
  51722. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  51723. var i;
  51724. var u = 0;
  51725. var c = 0;
  51726. var n = 0;
  51727. this._resetCopy();
  51728. if (options && options.positionFunction) {
  51729. options.positionFunction(this._copy, idx, idxInShape);
  51730. this._mustUnrotateFixedNormals = true;
  51731. }
  51732. if (this._copy.rotationQuaternion) {
  51733. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51734. }
  51735. else {
  51736. this._yaw = this._copy.rotation.y;
  51737. this._pitch = this._copy.rotation.x;
  51738. this._roll = this._copy.rotation.z;
  51739. this._quaternionRotationYPR();
  51740. }
  51741. this._quaternionToRotationMatrix();
  51742. if (this._copy.translateFromPivot) {
  51743. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51744. }
  51745. else {
  51746. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  51747. }
  51748. for (i = 0; i < shape.length; i++) {
  51749. this._vertex.x = shape[i].x;
  51750. this._vertex.y = shape[i].y;
  51751. this._vertex.z = shape[i].z;
  51752. if (options && options.vertexFunction) {
  51753. options.vertexFunction(this._copy, this._vertex, i);
  51754. }
  51755. this._vertex.x *= this._copy.scaling.x;
  51756. this._vertex.y *= this._copy.scaling.y;
  51757. this._vertex.z *= this._copy.scaling.z;
  51758. this._vertex.x -= this._copy.pivot.x;
  51759. this._vertex.y -= this._copy.pivot.y;
  51760. this._vertex.z -= this._copy.pivot.z;
  51761. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51762. this._rotated.addInPlace(this._pivotBackTranslation);
  51763. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  51764. if (meshUV) {
  51765. 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);
  51766. u += 2;
  51767. }
  51768. if (this._copy.color) {
  51769. this._color = this._copy.color;
  51770. }
  51771. else if (meshCol && meshCol[c] !== undefined) {
  51772. this._color.r = meshCol[c];
  51773. this._color.g = meshCol[c + 1];
  51774. this._color.b = meshCol[c + 2];
  51775. this._color.a = meshCol[c + 3];
  51776. }
  51777. else {
  51778. this._color.r = 1.0;
  51779. this._color.g = 1.0;
  51780. this._color.b = 1.0;
  51781. this._color.a = 1.0;
  51782. }
  51783. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  51784. c += 4;
  51785. if (!this.recomputeNormals && meshNor) {
  51786. this._normal.x = meshNor[n];
  51787. this._normal.y = meshNor[n + 1];
  51788. this._normal.z = meshNor[n + 2];
  51789. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  51790. normals.push(this._normal.x, this._normal.y, this._normal.z);
  51791. n += 3;
  51792. }
  51793. }
  51794. for (i = 0; i < meshInd.length; i++) {
  51795. var current_ind = p + meshInd[i];
  51796. indices.push(current_ind);
  51797. if (current_ind > 65535) {
  51798. this._needs32Bits = true;
  51799. }
  51800. }
  51801. if (this._pickable) {
  51802. var nbfaces = meshInd.length / 3;
  51803. for (i = 0; i < nbfaces; i++) {
  51804. this.pickedParticles.push({ idx: idx, faceId: i });
  51805. }
  51806. }
  51807. if (this._depthSort) {
  51808. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  51809. }
  51810. return this._copy;
  51811. };
  51812. // returns a shape array from positions array
  51813. SolidParticleSystem.prototype._posToShape = function (positions) {
  51814. var shape = [];
  51815. for (var i = 0; i < positions.length; i += 3) {
  51816. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  51817. }
  51818. return shape;
  51819. };
  51820. // returns a shapeUV array from a Vector4 uvs
  51821. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  51822. var shapeUV = [];
  51823. if (uvs) {
  51824. for (var i = 0; i < uvs.length; i++)
  51825. shapeUV.push(uvs[i]);
  51826. }
  51827. return shapeUV;
  51828. };
  51829. // adds a new particle object in the particles array
  51830. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  51831. if (bInfo === void 0) { bInfo = null; }
  51832. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  51833. this.particles.push(sp);
  51834. return sp;
  51835. };
  51836. /**
  51837. * Adds some particles to the SPS from the model shape. Returns the shape id.
  51838. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  51839. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  51840. * @param nb (positive integer) the number of particles to be created from this model
  51841. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  51842. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  51843. * @returns the number of shapes in the system
  51844. */
  51845. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  51846. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51847. var meshInd = mesh.getIndices();
  51848. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51849. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51850. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51851. var bbInfo;
  51852. if (this._particlesIntersect) {
  51853. bbInfo = mesh.getBoundingInfo();
  51854. }
  51855. var shape = this._posToShape(meshPos);
  51856. var shapeUV = this._uvsToShapeUV(meshUV);
  51857. var posfunc = options ? options.positionFunction : null;
  51858. var vtxfunc = options ? options.vertexFunction : null;
  51859. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  51860. // particles
  51861. var sp;
  51862. var currentCopy;
  51863. var idx = this.nbParticles;
  51864. for (var i = 0; i < nb; i++) {
  51865. var currentPos = this._positions.length;
  51866. var currentInd = this._indices.length;
  51867. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  51868. if (this._updatable) {
  51869. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  51870. sp.position.copyFrom(currentCopy.position);
  51871. sp.rotation.copyFrom(currentCopy.rotation);
  51872. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  51873. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  51874. }
  51875. if (currentCopy.color && sp.color) {
  51876. sp.color.copyFrom(currentCopy.color);
  51877. }
  51878. sp.scaling.copyFrom(currentCopy.scaling);
  51879. sp.uvs.copyFrom(currentCopy.uvs);
  51880. }
  51881. this._index += shape.length;
  51882. idx++;
  51883. }
  51884. this.nbParticles += nb;
  51885. this._shapeCounter++;
  51886. return this._shapeCounter - 1;
  51887. };
  51888. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  51889. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  51890. this._resetCopy();
  51891. if (particle._model._positionFunction) {
  51892. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  51893. }
  51894. if (this._copy.rotationQuaternion) {
  51895. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51896. }
  51897. else {
  51898. this._yaw = this._copy.rotation.y;
  51899. this._pitch = this._copy.rotation.x;
  51900. this._roll = this._copy.rotation.z;
  51901. this._quaternionRotationYPR();
  51902. }
  51903. this._quaternionToRotationMatrix();
  51904. if (this._copy.translateFromPivot) {
  51905. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51906. }
  51907. else {
  51908. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  51909. }
  51910. this._shape = particle._model._shape;
  51911. for (var pt = 0; pt < this._shape.length; pt++) {
  51912. this._vertex.x = this._shape[pt].x;
  51913. this._vertex.y = this._shape[pt].y;
  51914. this._vertex.z = this._shape[pt].z;
  51915. if (particle._model._vertexFunction) {
  51916. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  51917. }
  51918. this._vertex.x *= this._copy.scaling.x;
  51919. this._vertex.y *= this._copy.scaling.y;
  51920. this._vertex.z *= this._copy.scaling.z;
  51921. this._vertex.x -= this._copy.pivot.x;
  51922. this._vertex.y -= this._copy.pivot.y;
  51923. this._vertex.z -= this._copy.pivot.z;
  51924. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51925. this._rotated.addInPlace(this._pivotBackTranslation);
  51926. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  51927. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  51928. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  51929. }
  51930. particle.position.x = 0.0;
  51931. particle.position.y = 0.0;
  51932. particle.position.z = 0.0;
  51933. particle.rotation.x = 0.0;
  51934. particle.rotation.y = 0.0;
  51935. particle.rotation.z = 0.0;
  51936. particle.rotationQuaternion = null;
  51937. particle.scaling.x = 1.0;
  51938. particle.scaling.y = 1.0;
  51939. particle.scaling.z = 1.0;
  51940. };
  51941. /**
  51942. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  51943. * @returns the SPS.
  51944. */
  51945. SolidParticleSystem.prototype.rebuildMesh = function () {
  51946. for (var p = 0; p < this.particles.length; p++) {
  51947. this._rebuildParticle(this.particles[p]);
  51948. }
  51949. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  51950. return this;
  51951. };
  51952. /**
  51953. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  51954. * This method calls `updateParticle()` for each particle of the SPS.
  51955. * For an animated SPS, it is usually called within the render loop.
  51956. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  51957. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  51958. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  51959. * @returns the SPS.
  51960. */
  51961. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  51962. if (start === void 0) { start = 0; }
  51963. if (end === void 0) { end = this.nbParticles - 1; }
  51964. if (update === void 0) { update = true; }
  51965. if (!this._updatable) {
  51966. return this;
  51967. }
  51968. // custom beforeUpdate
  51969. this.beforeUpdateParticles(start, end, update);
  51970. this._cam_axisX.x = 1.0;
  51971. this._cam_axisX.y = 0.0;
  51972. this._cam_axisX.z = 0.0;
  51973. this._cam_axisY.x = 0.0;
  51974. this._cam_axisY.y = 1.0;
  51975. this._cam_axisY.z = 0.0;
  51976. this._cam_axisZ.x = 0.0;
  51977. this._cam_axisZ.y = 0.0;
  51978. this._cam_axisZ.z = 1.0;
  51979. // cases when the World Matrix is to be computed first
  51980. if (this.billboard || this._depthSort) {
  51981. this.mesh.computeWorldMatrix(true);
  51982. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  51983. }
  51984. // if the particles will always face the camera
  51985. if (this.billboard) {
  51986. // compute the camera position and un-rotate it by the current mesh rotation
  51987. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  51988. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  51989. this._cam_axisZ.normalize();
  51990. // same for camera up vector extracted from the cam view matrix
  51991. var view = this._camera.getViewMatrix(true);
  51992. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  51993. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  51994. this._cam_axisY.normalize();
  51995. this._cam_axisX.normalize();
  51996. }
  51997. // if depthSort, compute the camera global position in the mesh local system
  51998. if (this._depthSort) {
  51999. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  52000. }
  52001. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52002. var idx = 0; // current position index in the global array positions32
  52003. var index = 0; // position start index in the global array positions32 of the current particle
  52004. var colidx = 0; // current color index in the global array colors32
  52005. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52006. var uvidx = 0; // current uv index in the global array uvs32
  52007. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52008. var pt = 0; // current index in the particle model shape
  52009. if (this.mesh.isFacetDataEnabled) {
  52010. this._computeBoundingBox = true;
  52011. }
  52012. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52013. if (this._computeBoundingBox) {
  52014. if (start == 0 && end == this.nbParticles - 1) {
  52015. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52016. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52017. }
  52018. else {
  52019. if (this.mesh._boundingInfo) {
  52020. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52021. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52022. }
  52023. }
  52024. }
  52025. // particle loop
  52026. index = this.particles[start]._pos;
  52027. var vpos = (index / 3) | 0;
  52028. colorIndex = vpos * 4;
  52029. uvIndex = vpos * 2;
  52030. for (var p = start; p <= end; p++) {
  52031. this._particle = this.particles[p];
  52032. this._shape = this._particle._model._shape;
  52033. this._shapeUV = this._particle._model._shapeUV;
  52034. // call to custom user function to update the particle properties
  52035. this.updateParticle(this._particle);
  52036. // camera-particle distance for depth sorting
  52037. if (this._depthSort && this._depthSortParticles) {
  52038. var dsp = this.depthSortedParticles[p];
  52039. dsp.ind = this._particle._ind;
  52040. dsp.indicesLength = this._particle._model._indicesLength;
  52041. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  52042. }
  52043. // skip the computations for inactive or already invisible particles
  52044. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  52045. // increment indexes for the next particle
  52046. pt = this._shape.length;
  52047. index += pt * 3;
  52048. colorIndex += pt * 4;
  52049. uvIndex += pt * 2;
  52050. continue;
  52051. }
  52052. if (this._particle.isVisible) {
  52053. this._particle._stillInvisible = false; // un-mark permanent invisibility
  52054. // particle rotation matrix
  52055. if (this.billboard) {
  52056. this._particle.rotation.x = 0.0;
  52057. this._particle.rotation.y = 0.0;
  52058. }
  52059. if (this._computeParticleRotation || this.billboard) {
  52060. if (this._particle.rotationQuaternion) {
  52061. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52062. }
  52063. else {
  52064. this._yaw = this._particle.rotation.y;
  52065. this._pitch = this._particle.rotation.x;
  52066. this._roll = this._particle.rotation.z;
  52067. this._quaternionRotationYPR();
  52068. }
  52069. this._quaternionToRotationMatrix();
  52070. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  52071. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  52072. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  52073. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  52074. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  52075. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  52076. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  52077. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  52078. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  52079. }
  52080. if (this._particle.translateFromPivot) {
  52081. this._pivotBackTranslation.x = 0.0;
  52082. this._pivotBackTranslation.y = 0.0;
  52083. this._pivotBackTranslation.z = 0.0;
  52084. }
  52085. else {
  52086. this._pivotBackTranslation.x = this._particle.pivot.x;
  52087. this._pivotBackTranslation.y = this._particle.pivot.y;
  52088. this._pivotBackTranslation.z = this._particle.pivot.z;
  52089. }
  52090. // particle vertex loop
  52091. for (pt = 0; pt < this._shape.length; pt++) {
  52092. idx = index + pt * 3;
  52093. colidx = colorIndex + pt * 4;
  52094. uvidx = uvIndex + pt * 2;
  52095. this._vertex.x = this._shape[pt].x;
  52096. this._vertex.y = this._shape[pt].y;
  52097. this._vertex.z = this._shape[pt].z;
  52098. if (this._computeParticleVertex) {
  52099. this.updateParticleVertex(this._particle, this._vertex, pt);
  52100. }
  52101. // positions
  52102. this._vertex.x *= this._particle.scaling.x;
  52103. this._vertex.y *= this._particle.scaling.y;
  52104. this._vertex.z *= this._particle.scaling.z;
  52105. this._vertex.x -= this._particle.pivot.x;
  52106. this._vertex.y -= this._particle.pivot.y;
  52107. this._vertex.z -= this._particle.pivot.z;
  52108. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52109. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52110. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52111. this._rotated.x += this._pivotBackTranslation.x;
  52112. this._rotated.y += this._pivotBackTranslation.y;
  52113. this._rotated.z += this._pivotBackTranslation.z;
  52114. this._positions32[idx] = 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;
  52115. this._positions32[idx + 1] = 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;
  52116. this._positions32[idx + 2] = 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;
  52117. if (this._computeBoundingBox) {
  52118. if (this._positions32[idx] < this._minimum.x) {
  52119. this._minimum.x = this._positions32[idx];
  52120. }
  52121. if (this._positions32[idx] > this._maximum.x) {
  52122. this._maximum.x = this._positions32[idx];
  52123. }
  52124. if (this._positions32[idx + 1] < this._minimum.y) {
  52125. this._minimum.y = this._positions32[idx + 1];
  52126. }
  52127. if (this._positions32[idx + 1] > this._maximum.y) {
  52128. this._maximum.y = this._positions32[idx + 1];
  52129. }
  52130. if (this._positions32[idx + 2] < this._minimum.z) {
  52131. this._minimum.z = this._positions32[idx + 2];
  52132. }
  52133. if (this._positions32[idx + 2] > this._maximum.z) {
  52134. this._maximum.z = this._positions32[idx + 2];
  52135. }
  52136. }
  52137. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52138. if (!this._computeParticleVertex) {
  52139. this._normal.x = this._fixedNormal32[idx];
  52140. this._normal.y = this._fixedNormal32[idx + 1];
  52141. this._normal.z = this._fixedNormal32[idx + 2];
  52142. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  52143. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  52144. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  52145. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52146. 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;
  52147. 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;
  52148. }
  52149. if (this._computeParticleColor && this._particle.color) {
  52150. this._colors32[colidx] = this._particle.color.r;
  52151. this._colors32[colidx + 1] = this._particle.color.g;
  52152. this._colors32[colidx + 2] = this._particle.color.b;
  52153. this._colors32[colidx + 3] = this._particle.color.a;
  52154. }
  52155. if (this._computeParticleTexture) {
  52156. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52157. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52158. }
  52159. }
  52160. }
  52161. else {
  52162. this._particle._stillInvisible = true; // mark the particle as invisible
  52163. for (pt = 0; pt < this._shape.length; pt++) {
  52164. idx = index + pt * 3;
  52165. colidx = colorIndex + pt * 4;
  52166. uvidx = uvIndex + pt * 2;
  52167. this._positions32[idx] = 0.0;
  52168. this._positions32[idx + 1] = 0.0;
  52169. this._positions32[idx + 2] = 0.0;
  52170. this._normals32[idx] = 0.0;
  52171. this._normals32[idx + 1] = 0.0;
  52172. this._normals32[idx + 2] = 0.0;
  52173. if (this._computeParticleColor && this._particle.color) {
  52174. this._colors32[colidx] = this._particle.color.r;
  52175. this._colors32[colidx + 1] = this._particle.color.g;
  52176. this._colors32[colidx + 2] = this._particle.color.b;
  52177. this._colors32[colidx + 3] = this._particle.color.a;
  52178. }
  52179. if (this._computeParticleTexture) {
  52180. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52181. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52182. }
  52183. }
  52184. }
  52185. // if the particle intersections must be computed : update the bbInfo
  52186. if (this._particlesIntersect) {
  52187. var bInfo = this._particle._boundingInfo;
  52188. var bBox = bInfo.boundingBox;
  52189. var bSphere = bInfo.boundingSphere;
  52190. if (!this._bSphereOnly) {
  52191. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52192. for (var b = 0; b < bBox.vectors.length; b++) {
  52193. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52194. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52195. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52196. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52197. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52198. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52199. 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;
  52200. 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;
  52201. 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;
  52202. }
  52203. bBox._update(this.mesh._worldMatrix);
  52204. }
  52205. // place and scale the particle bouding sphere in the SPS local system, then update it
  52206. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52207. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52208. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52209. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52210. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52211. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52212. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52213. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52214. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52215. 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));
  52216. bSphere._update(this.mesh._worldMatrix);
  52217. }
  52218. // increment indexes for the next particle
  52219. index = idx + 3;
  52220. colorIndex = colidx + 4;
  52221. uvIndex = uvidx + 2;
  52222. }
  52223. // if the VBO must be updated
  52224. if (update) {
  52225. if (this._computeParticleColor) {
  52226. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52227. }
  52228. if (this._computeParticleTexture) {
  52229. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52230. }
  52231. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52232. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52233. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52234. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52235. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52236. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  52237. for (var i = 0; i < this._normals32.length; i++) {
  52238. this._fixedNormal32[i] = this._normals32[i];
  52239. }
  52240. }
  52241. if (!this.mesh.areNormalsFrozen) {
  52242. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52243. }
  52244. }
  52245. if (this._depthSort && this._depthSortParticles) {
  52246. this.depthSortedParticles.sort(this._depthSortFunction);
  52247. var dspl = this.depthSortedParticles.length;
  52248. var sorted = 0;
  52249. var lind = 0;
  52250. var sind = 0;
  52251. var sid = 0;
  52252. for (sorted = 0; sorted < dspl; sorted++) {
  52253. lind = this.depthSortedParticles[sorted].indicesLength;
  52254. sind = this.depthSortedParticles[sorted].ind;
  52255. for (var i = 0; i < lind; i++) {
  52256. this._indices32[sid] = this._indices[sind + i];
  52257. sid++;
  52258. }
  52259. }
  52260. this.mesh.updateIndices(this._indices32);
  52261. }
  52262. }
  52263. if (this._computeBoundingBox) {
  52264. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52265. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52266. }
  52267. this.afterUpdateParticles(start, end, update);
  52268. return this;
  52269. };
  52270. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52271. this._halfroll = this._roll * 0.5;
  52272. this._halfpitch = this._pitch * 0.5;
  52273. this._halfyaw = this._yaw * 0.5;
  52274. this._sinRoll = Math.sin(this._halfroll);
  52275. this._cosRoll = Math.cos(this._halfroll);
  52276. this._sinPitch = Math.sin(this._halfpitch);
  52277. this._cosPitch = Math.cos(this._halfpitch);
  52278. this._sinYaw = Math.sin(this._halfyaw);
  52279. this._cosYaw = Math.cos(this._halfyaw);
  52280. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  52281. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  52282. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  52283. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  52284. };
  52285. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52286. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52287. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52288. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52289. this._rotMatrix.m[3] = 0;
  52290. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52291. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52292. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52293. this._rotMatrix.m[7] = 0;
  52294. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52295. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52296. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52297. this._rotMatrix.m[11] = 0;
  52298. this._rotMatrix.m[12] = 0;
  52299. this._rotMatrix.m[13] = 0;
  52300. this._rotMatrix.m[14] = 0;
  52301. this._rotMatrix.m[15] = 1.0;
  52302. };
  52303. /**
  52304. * Disposes the SPS.
  52305. */
  52306. SolidParticleSystem.prototype.dispose = function () {
  52307. this.mesh.dispose();
  52308. this.vars = null;
  52309. // drop references to internal big arrays for the GC
  52310. this._positions = null;
  52311. this._indices = null;
  52312. this._normals = null;
  52313. this._uvs = null;
  52314. this._colors = null;
  52315. this._indices32 = null;
  52316. this._positions32 = null;
  52317. this._normals32 = null;
  52318. this._fixedNormal32 = null;
  52319. this._uvs32 = null;
  52320. this._colors32 = null;
  52321. this.pickedParticles = null;
  52322. };
  52323. /**
  52324. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  52325. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52326. * @returns the SPS.
  52327. */
  52328. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  52329. if (!this._isVisibilityBoxLocked) {
  52330. this.mesh.refreshBoundingInfo();
  52331. }
  52332. return this;
  52333. };
  52334. /**
  52335. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  52336. * @param size the size (float) of the visibility box
  52337. * note : this doesn't lock the SPS mesh bounding box.
  52338. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52339. */
  52340. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  52341. var vis = size / 2;
  52342. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  52343. };
  52344. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  52345. /**
  52346. * Gets whether the SPS as always visible or not
  52347. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52348. */
  52349. get: function () {
  52350. return this._alwaysVisible;
  52351. },
  52352. /**
  52353. * Sets the SPS as always visible or not
  52354. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52355. */
  52356. set: function (val) {
  52357. this._alwaysVisible = val;
  52358. this.mesh.alwaysSelectAsActiveMesh = val;
  52359. },
  52360. enumerable: true,
  52361. configurable: true
  52362. });
  52363. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  52364. /**
  52365. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52366. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52367. */
  52368. get: function () {
  52369. return this._isVisibilityBoxLocked;
  52370. },
  52371. /**
  52372. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52373. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52374. */
  52375. set: function (val) {
  52376. this._isVisibilityBoxLocked = val;
  52377. var boundingInfo = this.mesh.getBoundingInfo();
  52378. boundingInfo.isLocked = val;
  52379. },
  52380. enumerable: true,
  52381. configurable: true
  52382. });
  52383. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  52384. /**
  52385. * Gets if `setParticles()` computes the particle rotations or not.
  52386. * Default value : true. The SPS is faster when it's set to false.
  52387. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52388. */
  52389. get: function () {
  52390. return this._computeParticleRotation;
  52391. },
  52392. /**
  52393. * Tells to `setParticles()` to compute the particle rotations or not.
  52394. * Default value : true. The SPS is faster when it's set to false.
  52395. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52396. */
  52397. set: function (val) {
  52398. this._computeParticleRotation = val;
  52399. },
  52400. enumerable: true,
  52401. configurable: true
  52402. });
  52403. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  52404. /**
  52405. * Gets if `setParticles()` computes the particle colors or not.
  52406. * Default value : true. The SPS is faster when it's set to false.
  52407. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52408. */
  52409. get: function () {
  52410. return this._computeParticleColor;
  52411. },
  52412. /**
  52413. * Tells to `setParticles()` to compute the particle colors or not.
  52414. * Default value : true. The SPS is faster when it's set to false.
  52415. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52416. */
  52417. set: function (val) {
  52418. this._computeParticleColor = val;
  52419. },
  52420. enumerable: true,
  52421. configurable: true
  52422. });
  52423. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  52424. /**
  52425. * Gets if `setParticles()` computes the particle textures or not.
  52426. * Default value : true. The SPS is faster when it's set to false.
  52427. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  52428. */
  52429. get: function () {
  52430. return this._computeParticleTexture;
  52431. },
  52432. set: function (val) {
  52433. this._computeParticleTexture = val;
  52434. },
  52435. enumerable: true,
  52436. configurable: true
  52437. });
  52438. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  52439. /**
  52440. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  52441. * Default value : false. The SPS is faster when it's set to false.
  52442. * Note : the particle custom vertex positions aren't stored values.
  52443. */
  52444. get: function () {
  52445. return this._computeParticleVertex;
  52446. },
  52447. /**
  52448. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  52449. * Default value : false. The SPS is faster when it's set to false.
  52450. * Note : the particle custom vertex positions aren't stored values.
  52451. */
  52452. set: function (val) {
  52453. this._computeParticleVertex = val;
  52454. },
  52455. enumerable: true,
  52456. configurable: true
  52457. });
  52458. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  52459. /**
  52460. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  52461. */
  52462. get: function () {
  52463. return this._computeBoundingBox;
  52464. },
  52465. /**
  52466. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  52467. */
  52468. set: function (val) {
  52469. this._computeBoundingBox = val;
  52470. },
  52471. enumerable: true,
  52472. configurable: true
  52473. });
  52474. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  52475. /**
  52476. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  52477. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52478. * Default : `true`
  52479. */
  52480. get: function () {
  52481. return this._depthSortParticles;
  52482. },
  52483. /**
  52484. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  52485. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52486. * Default : `true`
  52487. */
  52488. set: function (val) {
  52489. this._depthSortParticles = val;
  52490. },
  52491. enumerable: true,
  52492. configurable: true
  52493. });
  52494. // =======================================================================
  52495. // Particle behavior logic
  52496. // these following methods may be overwritten by the user to fit his needs
  52497. /**
  52498. * This function does nothing. It may be overwritten to set all the particle first values.
  52499. * The SPS doesn't call this function, you may have to call it by your own.
  52500. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52501. */
  52502. SolidParticleSystem.prototype.initParticles = function () {
  52503. };
  52504. /**
  52505. * This function does nothing. It may be overwritten to recycle a particle.
  52506. * The SPS doesn't call this function, you may have to call it by your own.
  52507. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52508. * @param particle The particle to recycle
  52509. * @returns the recycled particle
  52510. */
  52511. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  52512. return particle;
  52513. };
  52514. /**
  52515. * Updates a particle : this function should be overwritten by the user.
  52516. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  52517. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52518. * @example : just set a particle position or velocity and recycle conditions
  52519. * @param particle The particle to update
  52520. * @returns the updated particle
  52521. */
  52522. SolidParticleSystem.prototype.updateParticle = function (particle) {
  52523. return particle;
  52524. };
  52525. /**
  52526. * Updates a vertex of a particle : it can be overwritten by the user.
  52527. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  52528. * @param particle the current particle
  52529. * @param vertex the current index of the current particle
  52530. * @param pt the index of the current vertex in the particle shape
  52531. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  52532. * @example : just set a vertex particle position
  52533. * @returns the updated vertex
  52534. */
  52535. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  52536. return vertex;
  52537. };
  52538. /**
  52539. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  52540. * This does nothing and may be overwritten by the user.
  52541. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52542. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52543. * @param update the boolean update value actually passed to setParticles()
  52544. */
  52545. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  52546. };
  52547. /**
  52548. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  52549. * This will be passed three parameters.
  52550. * This does nothing and may be overwritten by the user.
  52551. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52552. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52553. * @param update the boolean update value actually passed to setParticles()
  52554. */
  52555. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  52556. };
  52557. return SolidParticleSystem;
  52558. }());
  52559. BABYLON.SolidParticleSystem = SolidParticleSystem;
  52560. })(BABYLON || (BABYLON = {}));
  52561. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  52562. var BABYLON;
  52563. (function (BABYLON) {
  52564. var ShaderMaterial = /** @class */ (function (_super) {
  52565. __extends(ShaderMaterial, _super);
  52566. function ShaderMaterial(name, scene, shaderPath, options) {
  52567. var _this = _super.call(this, name, scene) || this;
  52568. _this._textures = {};
  52569. _this._textureArrays = {};
  52570. _this._floats = {};
  52571. _this._ints = {};
  52572. _this._floatsArrays = {};
  52573. _this._colors3 = {};
  52574. _this._colors3Arrays = {};
  52575. _this._colors4 = {};
  52576. _this._vectors2 = {};
  52577. _this._vectors3 = {};
  52578. _this._vectors4 = {};
  52579. _this._matrices = {};
  52580. _this._matrices3x3 = {};
  52581. _this._matrices2x2 = {};
  52582. _this._vectors2Arrays = {};
  52583. _this._vectors3Arrays = {};
  52584. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  52585. _this._shaderPath = shaderPath;
  52586. options.needAlphaBlending = options.needAlphaBlending || false;
  52587. options.needAlphaTesting = options.needAlphaTesting || false;
  52588. options.attributes = options.attributes || ["position", "normal", "uv"];
  52589. options.uniforms = options.uniforms || ["worldViewProjection"];
  52590. options.uniformBuffers = options.uniformBuffers || [];
  52591. options.samplers = options.samplers || [];
  52592. options.defines = options.defines || [];
  52593. _this._options = options;
  52594. return _this;
  52595. }
  52596. ShaderMaterial.prototype.getClassName = function () {
  52597. return "ShaderMaterial";
  52598. };
  52599. ShaderMaterial.prototype.needAlphaBlending = function () {
  52600. return this._options.needAlphaBlending;
  52601. };
  52602. ShaderMaterial.prototype.needAlphaTesting = function () {
  52603. return this._options.needAlphaTesting;
  52604. };
  52605. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  52606. if (this._options.uniforms.indexOf(uniformName) === -1) {
  52607. this._options.uniforms.push(uniformName);
  52608. }
  52609. };
  52610. ShaderMaterial.prototype.setTexture = function (name, texture) {
  52611. if (this._options.samplers.indexOf(name) === -1) {
  52612. this._options.samplers.push(name);
  52613. }
  52614. this._textures[name] = texture;
  52615. return this;
  52616. };
  52617. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  52618. if (this._options.samplers.indexOf(name) === -1) {
  52619. this._options.samplers.push(name);
  52620. }
  52621. this._checkUniform(name);
  52622. this._textureArrays[name] = textures;
  52623. return this;
  52624. };
  52625. ShaderMaterial.prototype.setFloat = function (name, value) {
  52626. this._checkUniform(name);
  52627. this._floats[name] = value;
  52628. return this;
  52629. };
  52630. ShaderMaterial.prototype.setInt = function (name, value) {
  52631. this._checkUniform(name);
  52632. this._ints[name] = value;
  52633. return this;
  52634. };
  52635. ShaderMaterial.prototype.setFloats = function (name, value) {
  52636. this._checkUniform(name);
  52637. this._floatsArrays[name] = value;
  52638. return this;
  52639. };
  52640. ShaderMaterial.prototype.setColor3 = function (name, value) {
  52641. this._checkUniform(name);
  52642. this._colors3[name] = value;
  52643. return this;
  52644. };
  52645. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  52646. this._checkUniform(name);
  52647. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  52648. color.toArray(arr, arr.length);
  52649. return arr;
  52650. }, []);
  52651. return this;
  52652. };
  52653. ShaderMaterial.prototype.setColor4 = function (name, value) {
  52654. this._checkUniform(name);
  52655. this._colors4[name] = value;
  52656. return this;
  52657. };
  52658. ShaderMaterial.prototype.setVector2 = function (name, value) {
  52659. this._checkUniform(name);
  52660. this._vectors2[name] = value;
  52661. return this;
  52662. };
  52663. ShaderMaterial.prototype.setVector3 = function (name, value) {
  52664. this._checkUniform(name);
  52665. this._vectors3[name] = value;
  52666. return this;
  52667. };
  52668. ShaderMaterial.prototype.setVector4 = function (name, value) {
  52669. this._checkUniform(name);
  52670. this._vectors4[name] = value;
  52671. return this;
  52672. };
  52673. ShaderMaterial.prototype.setMatrix = function (name, value) {
  52674. this._checkUniform(name);
  52675. this._matrices[name] = value;
  52676. return this;
  52677. };
  52678. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  52679. this._checkUniform(name);
  52680. this._matrices3x3[name] = value;
  52681. return this;
  52682. };
  52683. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  52684. this._checkUniform(name);
  52685. this._matrices2x2[name] = value;
  52686. return this;
  52687. };
  52688. ShaderMaterial.prototype.setArray2 = function (name, value) {
  52689. this._checkUniform(name);
  52690. this._vectors2Arrays[name] = value;
  52691. return this;
  52692. };
  52693. ShaderMaterial.prototype.setArray3 = function (name, value) {
  52694. this._checkUniform(name);
  52695. this._vectors3Arrays[name] = value;
  52696. return this;
  52697. };
  52698. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  52699. if (!mesh) {
  52700. return true;
  52701. }
  52702. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  52703. return false;
  52704. }
  52705. return false;
  52706. };
  52707. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  52708. var scene = this.getScene();
  52709. var engine = scene.getEngine();
  52710. if (!this.checkReadyOnEveryCall) {
  52711. if (this._renderId === scene.getRenderId()) {
  52712. if (this._checkCache(scene, mesh, useInstances)) {
  52713. return true;
  52714. }
  52715. }
  52716. }
  52717. // Instances
  52718. var defines = [];
  52719. var attribs = [];
  52720. var fallbacks = new BABYLON.EffectFallbacks();
  52721. if (useInstances) {
  52722. defines.push("#define INSTANCES");
  52723. }
  52724. for (var index = 0; index < this._options.defines.length; index++) {
  52725. defines.push(this._options.defines[index]);
  52726. }
  52727. for (var index = 0; index < this._options.attributes.length; index++) {
  52728. attribs.push(this._options.attributes[index]);
  52729. }
  52730. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52731. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52732. defines.push("#define VERTEXCOLOR");
  52733. }
  52734. // Bones
  52735. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  52736. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52737. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52738. if (mesh.numBoneInfluencers > 4) {
  52739. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52740. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52741. }
  52742. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52743. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52744. fallbacks.addCPUSkinningFallback(0, mesh);
  52745. if (this._options.uniforms.indexOf("mBones") === -1) {
  52746. this._options.uniforms.push("mBones");
  52747. }
  52748. }
  52749. else {
  52750. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52751. }
  52752. // Textures
  52753. for (var name in this._textures) {
  52754. if (!this._textures[name].isReady()) {
  52755. return false;
  52756. }
  52757. }
  52758. // Alpha test
  52759. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  52760. defines.push("#define ALPHATEST");
  52761. }
  52762. var previousEffect = this._effect;
  52763. var join = defines.join("\n");
  52764. this._effect = engine.createEffect(this._shaderPath, {
  52765. attributes: attribs,
  52766. uniformsNames: this._options.uniforms,
  52767. uniformBuffersNames: this._options.uniformBuffers,
  52768. samplers: this._options.samplers,
  52769. defines: join,
  52770. fallbacks: fallbacks,
  52771. onCompiled: this.onCompiled,
  52772. onError: this.onError
  52773. }, engine);
  52774. if (!this._effect.isReady()) {
  52775. return false;
  52776. }
  52777. if (previousEffect !== this._effect) {
  52778. scene.resetCachedMaterial();
  52779. }
  52780. this._renderId = scene.getRenderId();
  52781. return true;
  52782. };
  52783. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52784. var scene = this.getScene();
  52785. if (!this._effect) {
  52786. return;
  52787. }
  52788. if (this._options.uniforms.indexOf("world") !== -1) {
  52789. this._effect.setMatrix("world", world);
  52790. }
  52791. if (this._options.uniforms.indexOf("worldView") !== -1) {
  52792. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  52793. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  52794. }
  52795. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  52796. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  52797. }
  52798. };
  52799. ShaderMaterial.prototype.bind = function (world, mesh) {
  52800. // Std values
  52801. this.bindOnlyWorldMatrix(world);
  52802. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  52803. if (this._options.uniforms.indexOf("view") !== -1) {
  52804. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  52805. }
  52806. if (this._options.uniforms.indexOf("projection") !== -1) {
  52807. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  52808. }
  52809. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  52810. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  52811. }
  52812. // Bones
  52813. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  52814. var name;
  52815. // Texture
  52816. for (name in this._textures) {
  52817. this._effect.setTexture(name, this._textures[name]);
  52818. }
  52819. // Texture arrays
  52820. for (name in this._textureArrays) {
  52821. this._effect.setTextureArray(name, this._textureArrays[name]);
  52822. }
  52823. // Int
  52824. for (name in this._ints) {
  52825. this._effect.setInt(name, this._ints[name]);
  52826. }
  52827. // Float
  52828. for (name in this._floats) {
  52829. this._effect.setFloat(name, this._floats[name]);
  52830. }
  52831. // Floats
  52832. for (name in this._floatsArrays) {
  52833. this._effect.setArray(name, this._floatsArrays[name]);
  52834. }
  52835. // Color3
  52836. for (name in this._colors3) {
  52837. this._effect.setColor3(name, this._colors3[name]);
  52838. }
  52839. for (name in this._colors3Arrays) {
  52840. this._effect.setArray3(name, this._colors3Arrays[name]);
  52841. }
  52842. // Color4
  52843. for (name in this._colors4) {
  52844. var color = this._colors4[name];
  52845. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  52846. }
  52847. // Vector2
  52848. for (name in this._vectors2) {
  52849. this._effect.setVector2(name, this._vectors2[name]);
  52850. }
  52851. // Vector3
  52852. for (name in this._vectors3) {
  52853. this._effect.setVector3(name, this._vectors3[name]);
  52854. }
  52855. // Vector4
  52856. for (name in this._vectors4) {
  52857. this._effect.setVector4(name, this._vectors4[name]);
  52858. }
  52859. // Matrix
  52860. for (name in this._matrices) {
  52861. this._effect.setMatrix(name, this._matrices[name]);
  52862. }
  52863. // Matrix 3x3
  52864. for (name in this._matrices3x3) {
  52865. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  52866. }
  52867. // Matrix 2x2
  52868. for (name in this._matrices2x2) {
  52869. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  52870. }
  52871. // Vector2Array
  52872. for (name in this._vectors2Arrays) {
  52873. this._effect.setArray2(name, this._vectors2Arrays[name]);
  52874. }
  52875. // Vector3Array
  52876. for (name in this._vectors3Arrays) {
  52877. this._effect.setArray3(name, this._vectors3Arrays[name]);
  52878. }
  52879. }
  52880. this._afterBind(mesh);
  52881. };
  52882. ShaderMaterial.prototype.getActiveTextures = function () {
  52883. var activeTextures = _super.prototype.getActiveTextures.call(this);
  52884. for (var name in this._textures) {
  52885. activeTextures.push(this._textures[name]);
  52886. }
  52887. for (var name in this._textureArrays) {
  52888. var array = this._textureArrays[name];
  52889. for (var index = 0; index < array.length; index++) {
  52890. activeTextures.push(array[index]);
  52891. }
  52892. }
  52893. return activeTextures;
  52894. };
  52895. ShaderMaterial.prototype.hasTexture = function (texture) {
  52896. if (_super.prototype.hasTexture.call(this, texture)) {
  52897. return true;
  52898. }
  52899. for (var name in this._textures) {
  52900. if (this._textures[name] === texture) {
  52901. return true;
  52902. }
  52903. }
  52904. for (var name in this._textureArrays) {
  52905. var array = this._textureArrays[name];
  52906. for (var index = 0; index < array.length; index++) {
  52907. if (array[index] === texture) {
  52908. return true;
  52909. }
  52910. }
  52911. }
  52912. return false;
  52913. };
  52914. ShaderMaterial.prototype.clone = function (name) {
  52915. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  52916. return newShaderMaterial;
  52917. };
  52918. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52919. if (forceDisposeTextures) {
  52920. var name;
  52921. for (name in this._textures) {
  52922. this._textures[name].dispose();
  52923. }
  52924. for (name in this._textureArrays) {
  52925. var array = this._textureArrays[name];
  52926. for (var index = 0; index < array.length; index++) {
  52927. array[index].dispose();
  52928. }
  52929. }
  52930. }
  52931. this._textures = {};
  52932. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52933. };
  52934. ShaderMaterial.prototype.serialize = function () {
  52935. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52936. serializationObject.customType = "BABYLON.ShaderMaterial";
  52937. serializationObject.options = this._options;
  52938. serializationObject.shaderPath = this._shaderPath;
  52939. var name;
  52940. // Texture
  52941. serializationObject.textures = {};
  52942. for (name in this._textures) {
  52943. serializationObject.textures[name] = this._textures[name].serialize();
  52944. }
  52945. // Texture arrays
  52946. serializationObject.textureArrays = {};
  52947. for (name in this._textureArrays) {
  52948. serializationObject.textureArrays[name] = [];
  52949. var array = this._textureArrays[name];
  52950. for (var index = 0; index < array.length; index++) {
  52951. serializationObject.textureArrays[name].push(array[index].serialize());
  52952. }
  52953. }
  52954. // Float
  52955. serializationObject.floats = {};
  52956. for (name in this._floats) {
  52957. serializationObject.floats[name] = this._floats[name];
  52958. }
  52959. // Float s
  52960. serializationObject.FloatArrays = {};
  52961. for (name in this._floatsArrays) {
  52962. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  52963. }
  52964. // Color3
  52965. serializationObject.colors3 = {};
  52966. for (name in this._colors3) {
  52967. serializationObject.colors3[name] = this._colors3[name].asArray();
  52968. }
  52969. // Color3 array
  52970. serializationObject.colors3Arrays = {};
  52971. for (name in this._colors3Arrays) {
  52972. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  52973. }
  52974. // Color4
  52975. serializationObject.colors4 = {};
  52976. for (name in this._colors4) {
  52977. serializationObject.colors4[name] = this._colors4[name].asArray();
  52978. }
  52979. // Vector2
  52980. serializationObject.vectors2 = {};
  52981. for (name in this._vectors2) {
  52982. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  52983. }
  52984. // Vector3
  52985. serializationObject.vectors3 = {};
  52986. for (name in this._vectors3) {
  52987. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  52988. }
  52989. // Vector4
  52990. serializationObject.vectors4 = {};
  52991. for (name in this._vectors4) {
  52992. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  52993. }
  52994. // Matrix
  52995. serializationObject.matrices = {};
  52996. for (name in this._matrices) {
  52997. serializationObject.matrices[name] = this._matrices[name].asArray();
  52998. }
  52999. // Matrix 3x3
  53000. serializationObject.matrices3x3 = {};
  53001. for (name in this._matrices3x3) {
  53002. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  53003. }
  53004. // Matrix 2x2
  53005. serializationObject.matrices2x2 = {};
  53006. for (name in this._matrices2x2) {
  53007. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  53008. }
  53009. // Vector2Array
  53010. serializationObject.vectors2Arrays = {};
  53011. for (name in this._vectors2Arrays) {
  53012. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  53013. }
  53014. // Vector3Array
  53015. serializationObject.vectors3Arrays = {};
  53016. for (name in this._vectors3Arrays) {
  53017. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  53018. }
  53019. return serializationObject;
  53020. };
  53021. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  53022. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  53023. var name;
  53024. // Texture
  53025. for (name in source.textures) {
  53026. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  53027. }
  53028. // Texture arrays
  53029. for (name in source.textureArrays) {
  53030. var array = source.textureArrays[name];
  53031. var textureArray = new Array();
  53032. for (var index = 0; index < array.length; index++) {
  53033. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  53034. }
  53035. material.setTextureArray(name, textureArray);
  53036. }
  53037. // Float
  53038. for (name in source.floats) {
  53039. material.setFloat(name, source.floats[name]);
  53040. }
  53041. // Float s
  53042. for (name in source.floatsArrays) {
  53043. material.setFloats(name, source.floatsArrays[name]);
  53044. }
  53045. // Color3
  53046. for (name in source.colors3) {
  53047. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  53048. }
  53049. // Color3 arrays
  53050. for (name in source.colors3Arrays) {
  53051. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  53052. if (i % 3 === 0) {
  53053. arr.push([num]);
  53054. }
  53055. else {
  53056. arr[arr.length - 1].push(num);
  53057. }
  53058. return arr;
  53059. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  53060. material.setColor3Array(name, colors);
  53061. }
  53062. // Color4
  53063. for (name in source.colors4) {
  53064. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  53065. }
  53066. // Vector2
  53067. for (name in source.vectors2) {
  53068. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  53069. }
  53070. // Vector3
  53071. for (name in source.vectors3) {
  53072. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  53073. }
  53074. // Vector4
  53075. for (name in source.vectors4) {
  53076. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  53077. }
  53078. // Matrix
  53079. for (name in source.matrices) {
  53080. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  53081. }
  53082. // Matrix 3x3
  53083. for (name in source.matrices3x3) {
  53084. material.setMatrix3x3(name, source.matrices3x3[name]);
  53085. }
  53086. // Matrix 2x2
  53087. for (name in source.matrices2x2) {
  53088. material.setMatrix2x2(name, source.matrices2x2[name]);
  53089. }
  53090. // Vector2Array
  53091. for (name in source.vectors2Arrays) {
  53092. material.setArray2(name, source.vectors2Arrays[name]);
  53093. }
  53094. // Vector3Array
  53095. for (name in source.vectors3Arrays) {
  53096. material.setArray3(name, source.vectors3Arrays[name]);
  53097. }
  53098. return material;
  53099. };
  53100. return ShaderMaterial;
  53101. }(BABYLON.Material));
  53102. BABYLON.ShaderMaterial = ShaderMaterial;
  53103. })(BABYLON || (BABYLON = {}));
  53104. //# sourceMappingURL=babylon.shaderMaterial.js.map
  53105. var BABYLON;
  53106. (function (BABYLON) {
  53107. var GroundMesh = /** @class */ (function (_super) {
  53108. __extends(GroundMesh, _super);
  53109. function GroundMesh(name, scene) {
  53110. var _this = _super.call(this, name, scene) || this;
  53111. _this.generateOctree = false;
  53112. return _this;
  53113. }
  53114. GroundMesh.prototype.getClassName = function () {
  53115. return "GroundMesh";
  53116. };
  53117. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  53118. get: function () {
  53119. return Math.min(this._subdivisionsX, this._subdivisionsY);
  53120. },
  53121. enumerable: true,
  53122. configurable: true
  53123. });
  53124. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53125. get: function () {
  53126. return this._subdivisionsX;
  53127. },
  53128. enumerable: true,
  53129. configurable: true
  53130. });
  53131. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  53132. get: function () {
  53133. return this._subdivisionsY;
  53134. },
  53135. enumerable: true,
  53136. configurable: true
  53137. });
  53138. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  53139. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  53140. this._subdivisionsX = chunksCount;
  53141. this._subdivisionsY = chunksCount;
  53142. this.subdivide(chunksCount);
  53143. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  53144. };
  53145. /**
  53146. * Returns a height (y) value in the Worl system :
  53147. * the ground altitude at the coordinates (x, z) expressed in the World system.
  53148. * Returns the ground y position if (x, z) are outside the ground surface.
  53149. */
  53150. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  53151. var world = this.getWorldMatrix();
  53152. var invMat = BABYLON.Tmp.Matrix[5];
  53153. world.invertToRef(invMat);
  53154. var tmpVect = BABYLON.Tmp.Vector3[8];
  53155. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  53156. x = tmpVect.x;
  53157. z = tmpVect.z;
  53158. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53159. return this.position.y;
  53160. }
  53161. if (!this._heightQuads || this._heightQuads.length == 0) {
  53162. this._initHeightQuads();
  53163. this._computeHeightQuads();
  53164. }
  53165. var facet = this._getFacetAt(x, z);
  53166. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  53167. // return y in the World system
  53168. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  53169. return tmpVect.y;
  53170. };
  53171. /**
  53172. * Returns a normalized vector (Vector3) orthogonal to the ground
  53173. * at the ground coordinates (x, z) expressed in the World system.
  53174. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  53175. */
  53176. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  53177. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  53178. this.getNormalAtCoordinatesToRef(x, z, normal);
  53179. return normal;
  53180. };
  53181. /**
  53182. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  53183. * at the ground coordinates (x, z) expressed in the World system.
  53184. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  53185. * Returns the GroundMesh.
  53186. */
  53187. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  53188. var world = this.getWorldMatrix();
  53189. var tmpMat = BABYLON.Tmp.Matrix[5];
  53190. world.invertToRef(tmpMat);
  53191. var tmpVect = BABYLON.Tmp.Vector3[8];
  53192. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  53193. x = tmpVect.x;
  53194. z = tmpVect.z;
  53195. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53196. return this;
  53197. }
  53198. if (!this._heightQuads || this._heightQuads.length == 0) {
  53199. this._initHeightQuads();
  53200. this._computeHeightQuads();
  53201. }
  53202. var facet = this._getFacetAt(x, z);
  53203. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  53204. return this;
  53205. };
  53206. /**
  53207. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  53208. * if the ground has been updated.
  53209. * This can be used in the render loop.
  53210. * Returns the GroundMesh.
  53211. */
  53212. GroundMesh.prototype.updateCoordinateHeights = function () {
  53213. if (!this._heightQuads || this._heightQuads.length == 0) {
  53214. this._initHeightQuads();
  53215. }
  53216. this._computeHeightQuads();
  53217. return this;
  53218. };
  53219. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  53220. GroundMesh.prototype._getFacetAt = function (x, z) {
  53221. // retrieve col and row from x, z coordinates in the ground local system
  53222. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  53223. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  53224. var quad = this._heightQuads[row * this._subdivisionsX + col];
  53225. var facet;
  53226. if (z < quad.slope.x * x + quad.slope.y) {
  53227. facet = quad.facet1;
  53228. }
  53229. else {
  53230. facet = quad.facet2;
  53231. }
  53232. return facet;
  53233. };
  53234. // Creates and populates the heightMap array with "facet" elements :
  53235. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  53236. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53237. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53238. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53239. // Returns the GroundMesh.
  53240. GroundMesh.prototype._initHeightQuads = function () {
  53241. var subdivisionsX = this._subdivisionsX;
  53242. var subdivisionsY = this._subdivisionsY;
  53243. this._heightQuads = new Array();
  53244. for (var row = 0; row < subdivisionsY; row++) {
  53245. for (var col = 0; col < subdivisionsX; col++) {
  53246. 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) };
  53247. this._heightQuads[row * subdivisionsX + col] = quad;
  53248. }
  53249. }
  53250. return this;
  53251. };
  53252. // Compute each quad element values and update the the heightMap array :
  53253. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53254. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53255. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53256. // Returns the GroundMesh.
  53257. GroundMesh.prototype._computeHeightQuads = function () {
  53258. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53259. if (!positions) {
  53260. return this;
  53261. }
  53262. var v1 = BABYLON.Tmp.Vector3[3];
  53263. var v2 = BABYLON.Tmp.Vector3[2];
  53264. var v3 = BABYLON.Tmp.Vector3[1];
  53265. var v4 = BABYLON.Tmp.Vector3[0];
  53266. var v1v2 = BABYLON.Tmp.Vector3[4];
  53267. var v1v3 = BABYLON.Tmp.Vector3[5];
  53268. var v1v4 = BABYLON.Tmp.Vector3[6];
  53269. var norm1 = BABYLON.Tmp.Vector3[7];
  53270. var norm2 = BABYLON.Tmp.Vector3[8];
  53271. var i = 0;
  53272. var j = 0;
  53273. var k = 0;
  53274. var cd = 0; // 2D slope coefficient : z = cd * x + h
  53275. var h = 0;
  53276. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  53277. var d2 = 0;
  53278. var subdivisionsX = this._subdivisionsX;
  53279. var subdivisionsY = this._subdivisionsY;
  53280. for (var row = 0; row < subdivisionsY; row++) {
  53281. for (var col = 0; col < subdivisionsX; col++) {
  53282. i = col * 3;
  53283. j = row * (subdivisionsX + 1) * 3;
  53284. k = (row + 1) * (subdivisionsX + 1) * 3;
  53285. v1.x = positions[j + i];
  53286. v1.y = positions[j + i + 1];
  53287. v1.z = positions[j + i + 2];
  53288. v2.x = positions[j + i + 3];
  53289. v2.y = positions[j + i + 4];
  53290. v2.z = positions[j + i + 5];
  53291. v3.x = positions[k + i];
  53292. v3.y = positions[k + i + 1];
  53293. v3.z = positions[k + i + 2];
  53294. v4.x = positions[k + i + 3];
  53295. v4.y = positions[k + i + 4];
  53296. v4.z = positions[k + i + 5];
  53297. // 2D slope V1V4
  53298. cd = (v4.z - v1.z) / (v4.x - v1.x);
  53299. h = v1.z - cd * v1.x; // v1 belongs to the slope
  53300. // facet equations :
  53301. // we compute each facet normal vector
  53302. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  53303. // we compute the value d by applying the equation to v1 which belongs to the plane
  53304. // then we store the facet equation in a Vector4
  53305. v2.subtractToRef(v1, v1v2);
  53306. v3.subtractToRef(v1, v1v3);
  53307. v4.subtractToRef(v1, v1v4);
  53308. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  53309. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  53310. norm1.normalize();
  53311. norm2.normalize();
  53312. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  53313. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  53314. var quad = this._heightQuads[row * subdivisionsX + col];
  53315. quad.slope.copyFromFloats(cd, h);
  53316. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  53317. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  53318. }
  53319. }
  53320. return this;
  53321. };
  53322. GroundMesh.prototype.serialize = function (serializationObject) {
  53323. _super.prototype.serialize.call(this, serializationObject);
  53324. serializationObject.subdivisionsX = this._subdivisionsX;
  53325. serializationObject.subdivisionsY = this._subdivisionsY;
  53326. serializationObject.minX = this._minX;
  53327. serializationObject.maxX = this._maxX;
  53328. serializationObject.minZ = this._minZ;
  53329. serializationObject.maxZ = this._maxZ;
  53330. serializationObject.width = this._width;
  53331. serializationObject.height = this._height;
  53332. };
  53333. GroundMesh.Parse = function (parsedMesh, scene) {
  53334. var result = new GroundMesh(parsedMesh.name, scene);
  53335. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  53336. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  53337. result._minX = parsedMesh.minX;
  53338. result._maxX = parsedMesh.maxX;
  53339. result._minZ = parsedMesh.minZ;
  53340. result._maxZ = parsedMesh.maxZ;
  53341. result._width = parsedMesh.width;
  53342. result._height = parsedMesh.height;
  53343. return result;
  53344. };
  53345. return GroundMesh;
  53346. }(BABYLON.Mesh));
  53347. BABYLON.GroundMesh = GroundMesh;
  53348. })(BABYLON || (BABYLON = {}));
  53349. //# sourceMappingURL=babylon.groundMesh.js.map
  53350. var BABYLON;
  53351. (function (BABYLON) {
  53352. /**
  53353. * Creates an instance based on a source mesh.
  53354. */
  53355. var InstancedMesh = /** @class */ (function (_super) {
  53356. __extends(InstancedMesh, _super);
  53357. function InstancedMesh(name, source) {
  53358. var _this = _super.call(this, name, source.getScene()) || this;
  53359. source.instances.push(_this);
  53360. _this._sourceMesh = source;
  53361. _this.position.copyFrom(source.position);
  53362. _this.rotation.copyFrom(source.rotation);
  53363. _this.scaling.copyFrom(source.scaling);
  53364. if (source.rotationQuaternion) {
  53365. _this.rotationQuaternion = source.rotationQuaternion.clone();
  53366. }
  53367. _this.infiniteDistance = source.infiniteDistance;
  53368. _this.setPivotMatrix(source.getPivotMatrix());
  53369. _this.refreshBoundingInfo();
  53370. _this._syncSubMeshes();
  53371. return _this;
  53372. }
  53373. /**
  53374. * Returns the string "InstancedMesh".
  53375. */
  53376. InstancedMesh.prototype.getClassName = function () {
  53377. return "InstancedMesh";
  53378. };
  53379. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  53380. // Methods
  53381. get: function () {
  53382. return this._sourceMesh.receiveShadows;
  53383. },
  53384. enumerable: true,
  53385. configurable: true
  53386. });
  53387. Object.defineProperty(InstancedMesh.prototype, "material", {
  53388. get: function () {
  53389. return this._sourceMesh.material;
  53390. },
  53391. enumerable: true,
  53392. configurable: true
  53393. });
  53394. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  53395. get: function () {
  53396. return this._sourceMesh.visibility;
  53397. },
  53398. enumerable: true,
  53399. configurable: true
  53400. });
  53401. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  53402. get: function () {
  53403. return this._sourceMesh.skeleton;
  53404. },
  53405. enumerable: true,
  53406. configurable: true
  53407. });
  53408. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  53409. get: function () {
  53410. return this._sourceMesh.renderingGroupId;
  53411. },
  53412. enumerable: true,
  53413. configurable: true
  53414. });
  53415. /**
  53416. * Returns the total number of vertices (integer).
  53417. */
  53418. InstancedMesh.prototype.getTotalVertices = function () {
  53419. return this._sourceMesh.getTotalVertices();
  53420. };
  53421. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  53422. get: function () {
  53423. return this._sourceMesh;
  53424. },
  53425. enumerable: true,
  53426. configurable: true
  53427. });
  53428. /**
  53429. * Is this node ready to be used/rendered
  53430. * @return {boolean} is it ready
  53431. */
  53432. InstancedMesh.prototype.isReady = function () {
  53433. return this._sourceMesh.isReady(true);
  53434. };
  53435. /**
  53436. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  53437. */
  53438. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  53439. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  53440. };
  53441. /**
  53442. * Sets the vertex data of the mesh geometry for the requested `kind`.
  53443. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  53444. * The `data` are either a numeric array either a Float32Array.
  53445. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  53446. * 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).
  53447. * Note that a new underlying VertexBuffer object is created each call.
  53448. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  53449. *
  53450. * Possible `kind` values :
  53451. * - BABYLON.VertexBuffer.PositionKind
  53452. * - BABYLON.VertexBuffer.UVKind
  53453. * - BABYLON.VertexBuffer.UV2Kind
  53454. * - BABYLON.VertexBuffer.UV3Kind
  53455. * - BABYLON.VertexBuffer.UV4Kind
  53456. * - BABYLON.VertexBuffer.UV5Kind
  53457. * - BABYLON.VertexBuffer.UV6Kind
  53458. * - BABYLON.VertexBuffer.ColorKind
  53459. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53460. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53461. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53462. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53463. *
  53464. * Returns the Mesh.
  53465. */
  53466. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  53467. if (this.sourceMesh) {
  53468. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  53469. }
  53470. return this.sourceMesh;
  53471. };
  53472. /**
  53473. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  53474. * If the mesh has no geometry, it is simply returned as it is.
  53475. * The `data` are either a numeric array either a Float32Array.
  53476. * No new underlying VertexBuffer object is created.
  53477. * 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.
  53478. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  53479. *
  53480. * Possible `kind` values :
  53481. * - BABYLON.VertexBuffer.PositionKind
  53482. * - BABYLON.VertexBuffer.UVKind
  53483. * - BABYLON.VertexBuffer.UV2Kind
  53484. * - BABYLON.VertexBuffer.UV3Kind
  53485. * - BABYLON.VertexBuffer.UV4Kind
  53486. * - BABYLON.VertexBuffer.UV5Kind
  53487. * - BABYLON.VertexBuffer.UV6Kind
  53488. * - BABYLON.VertexBuffer.ColorKind
  53489. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53490. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53491. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53492. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53493. *
  53494. * Returns the Mesh.
  53495. */
  53496. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  53497. if (this.sourceMesh) {
  53498. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  53499. }
  53500. return this.sourceMesh;
  53501. };
  53502. /**
  53503. * Sets the mesh indices.
  53504. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  53505. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  53506. * This method creates a new index buffer each call.
  53507. * Returns the Mesh.
  53508. */
  53509. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  53510. if (totalVertices === void 0) { totalVertices = null; }
  53511. if (this.sourceMesh) {
  53512. this.sourceMesh.setIndices(indices, totalVertices);
  53513. }
  53514. return this.sourceMesh;
  53515. };
  53516. /**
  53517. * Boolean : True if the mesh owns the requested kind of data.
  53518. */
  53519. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  53520. return this._sourceMesh.isVerticesDataPresent(kind);
  53521. };
  53522. /**
  53523. * Returns an array of indices (IndicesArray).
  53524. */
  53525. InstancedMesh.prototype.getIndices = function () {
  53526. return this._sourceMesh.getIndices();
  53527. };
  53528. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  53529. get: function () {
  53530. return this._sourceMesh._positions;
  53531. },
  53532. enumerable: true,
  53533. configurable: true
  53534. });
  53535. /**
  53536. * Sets a new updated BoundingInfo to the mesh.
  53537. * Returns the mesh.
  53538. */
  53539. InstancedMesh.prototype.refreshBoundingInfo = function () {
  53540. var meshBB = this._sourceMesh.getBoundingInfo();
  53541. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  53542. this._updateBoundingInfo();
  53543. return this;
  53544. };
  53545. InstancedMesh.prototype._preActivate = function () {
  53546. if (this._currentLOD) {
  53547. this._currentLOD._preActivate();
  53548. }
  53549. return this;
  53550. };
  53551. InstancedMesh.prototype._activate = function (renderId) {
  53552. if (this._currentLOD) {
  53553. this._currentLOD._registerInstanceForRenderId(this, renderId);
  53554. }
  53555. return this;
  53556. };
  53557. /**
  53558. * Returns the current associated LOD AbstractMesh.
  53559. */
  53560. InstancedMesh.prototype.getLOD = function (camera) {
  53561. if (!camera) {
  53562. return this;
  53563. }
  53564. var boundingInfo = this.getBoundingInfo();
  53565. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  53566. if (this._currentLOD === this.sourceMesh) {
  53567. return this;
  53568. }
  53569. return this._currentLOD;
  53570. };
  53571. InstancedMesh.prototype._syncSubMeshes = function () {
  53572. this.releaseSubMeshes();
  53573. if (this._sourceMesh.subMeshes) {
  53574. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  53575. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  53576. }
  53577. }
  53578. return this;
  53579. };
  53580. InstancedMesh.prototype._generatePointsArray = function () {
  53581. return this._sourceMesh._generatePointsArray();
  53582. };
  53583. /**
  53584. * Creates a new InstancedMesh from the current mesh.
  53585. * - name (string) : the cloned mesh name
  53586. * - newParent (optional Node) : the optional Node to parent the clone to.
  53587. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  53588. *
  53589. * Returns the clone.
  53590. */
  53591. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53592. var result = this._sourceMesh.createInstance(name);
  53593. // Deep copy
  53594. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  53595. // Bounding info
  53596. this.refreshBoundingInfo();
  53597. // Parent
  53598. if (newParent) {
  53599. result.parent = newParent;
  53600. }
  53601. if (!doNotCloneChildren) {
  53602. // Children
  53603. for (var index = 0; index < this.getScene().meshes.length; index++) {
  53604. var mesh = this.getScene().meshes[index];
  53605. if (mesh.parent === this) {
  53606. mesh.clone(mesh.name, result);
  53607. }
  53608. }
  53609. }
  53610. result.computeWorldMatrix(true);
  53611. return result;
  53612. };
  53613. /**
  53614. * Disposes the InstancedMesh.
  53615. * Returns nothing.
  53616. */
  53617. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  53618. // Remove from mesh
  53619. var index = this._sourceMesh.instances.indexOf(this);
  53620. this._sourceMesh.instances.splice(index, 1);
  53621. _super.prototype.dispose.call(this, doNotRecurse);
  53622. };
  53623. return InstancedMesh;
  53624. }(BABYLON.AbstractMesh));
  53625. BABYLON.InstancedMesh = InstancedMesh;
  53626. })(BABYLON || (BABYLON = {}));
  53627. //# sourceMappingURL=babylon.instancedMesh.js.map
  53628. var BABYLON;
  53629. (function (BABYLON) {
  53630. var LinesMesh = /** @class */ (function (_super) {
  53631. __extends(LinesMesh, _super);
  53632. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  53633. if (scene === void 0) { scene = null; }
  53634. if (parent === void 0) { parent = null; }
  53635. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  53636. _this.useVertexColor = useVertexColor;
  53637. _this.useVertexAlpha = useVertexAlpha;
  53638. _this.color = new BABYLON.Color3(1, 1, 1);
  53639. _this.alpha = 1;
  53640. if (source) {
  53641. _this.color = source.color.clone();
  53642. _this.alpha = source.alpha;
  53643. _this.useVertexColor = source.useVertexColor;
  53644. _this.useVertexAlpha = source.useVertexAlpha;
  53645. }
  53646. _this._intersectionThreshold = 0.1;
  53647. var defines = [];
  53648. var options = {
  53649. attributes: [BABYLON.VertexBuffer.PositionKind],
  53650. uniforms: ["world", "viewProjection"],
  53651. needAlphaBlending: true,
  53652. defines: defines
  53653. };
  53654. if (useVertexAlpha === false) {
  53655. options.needAlphaBlending = false;
  53656. }
  53657. if (!useVertexColor) {
  53658. options.uniforms.push("color");
  53659. }
  53660. else {
  53661. options.defines.push("#define VERTEXCOLOR");
  53662. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  53663. }
  53664. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  53665. return _this;
  53666. }
  53667. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  53668. /**
  53669. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53670. * This margin is expressed in world space coordinates, so its value may vary.
  53671. * Default value is 0.1
  53672. * @returns the intersection Threshold value.
  53673. */
  53674. get: function () {
  53675. return this._intersectionThreshold;
  53676. },
  53677. /**
  53678. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53679. * This margin is expressed in world space coordinates, so its value may vary.
  53680. * @param value the new threshold to apply
  53681. */
  53682. set: function (value) {
  53683. if (this._intersectionThreshold === value) {
  53684. return;
  53685. }
  53686. this._intersectionThreshold = value;
  53687. if (this.geometry) {
  53688. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  53689. }
  53690. },
  53691. enumerable: true,
  53692. configurable: true
  53693. });
  53694. /**
  53695. * Returns the string "LineMesh"
  53696. */
  53697. LinesMesh.prototype.getClassName = function () {
  53698. return "LinesMesh";
  53699. };
  53700. Object.defineProperty(LinesMesh.prototype, "material", {
  53701. get: function () {
  53702. return this._colorShader;
  53703. },
  53704. set: function (value) {
  53705. // Do nothing
  53706. },
  53707. enumerable: true,
  53708. configurable: true
  53709. });
  53710. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  53711. get: function () {
  53712. return false;
  53713. },
  53714. enumerable: true,
  53715. configurable: true
  53716. });
  53717. LinesMesh.prototype.createInstance = function (name) {
  53718. throw new Error("LinesMeshes do not support createInstance.");
  53719. };
  53720. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  53721. if (!this._geometry) {
  53722. return this;
  53723. }
  53724. // VBOs
  53725. this._geometry._bind(this._colorShader.getEffect());
  53726. // Color
  53727. if (!this.useVertexColor) {
  53728. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  53729. }
  53730. return this;
  53731. };
  53732. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  53733. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  53734. return this;
  53735. }
  53736. var engine = this.getScene().getEngine();
  53737. // Draw order
  53738. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  53739. return this;
  53740. };
  53741. LinesMesh.prototype.dispose = function (doNotRecurse) {
  53742. this._colorShader.dispose();
  53743. _super.prototype.dispose.call(this, doNotRecurse);
  53744. };
  53745. /**
  53746. * Returns a new LineMesh object cloned from the current one.
  53747. */
  53748. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53749. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  53750. };
  53751. return LinesMesh;
  53752. }(BABYLON.Mesh));
  53753. BABYLON.LinesMesh = LinesMesh;
  53754. })(BABYLON || (BABYLON = {}));
  53755. //# sourceMappingURL=babylon.linesMesh.js.map
  53756. var BABYLON;
  53757. (function (BABYLON) {
  53758. var MeshBuilder = /** @class */ (function () {
  53759. function MeshBuilder() {
  53760. }
  53761. MeshBuilder.updateSideOrientation = function (orientation) {
  53762. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  53763. return BABYLON.Mesh.DOUBLESIDE;
  53764. }
  53765. if (orientation === undefined || orientation === null) {
  53766. return BABYLON.Mesh.FRONTSIDE;
  53767. }
  53768. return orientation;
  53769. };
  53770. /**
  53771. * Creates a box mesh.
  53772. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  53773. * The parameter `size` sets the size (float) of each box side (default 1).
  53774. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  53775. * 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).
  53776. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  53777. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53778. * 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).
  53779. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53780. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53781. */
  53782. MeshBuilder.CreateBox = function (name, options, scene) {
  53783. if (scene === void 0) { scene = null; }
  53784. var box = new BABYLON.Mesh(name, scene);
  53785. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53786. box._originalBuilderSideOrientation = options.sideOrientation;
  53787. var vertexData = BABYLON.VertexData.CreateBox(options);
  53788. vertexData.applyToMesh(box, options.updatable);
  53789. return box;
  53790. };
  53791. /**
  53792. * Creates a sphere mesh.
  53793. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  53794. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  53795. * 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`).
  53796. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  53797. * 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
  53798. * 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).
  53799. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53800. * 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).
  53801. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53802. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53803. */
  53804. MeshBuilder.CreateSphere = function (name, options, scene) {
  53805. var sphere = new BABYLON.Mesh(name, scene);
  53806. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53807. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53808. var vertexData = BABYLON.VertexData.CreateSphere(options);
  53809. vertexData.applyToMesh(sphere, options.updatable);
  53810. return sphere;
  53811. };
  53812. /**
  53813. * Creates a plane polygonal mesh. By default, this is a disc.
  53814. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  53815. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  53816. * 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.
  53817. * 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
  53818. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53819. * 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).
  53820. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53821. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53822. */
  53823. MeshBuilder.CreateDisc = function (name, options, scene) {
  53824. if (scene === void 0) { scene = null; }
  53825. var disc = new BABYLON.Mesh(name, scene);
  53826. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53827. disc._originalBuilderSideOrientation = options.sideOrientation;
  53828. var vertexData = BABYLON.VertexData.CreateDisc(options);
  53829. vertexData.applyToMesh(disc, options.updatable);
  53830. return disc;
  53831. };
  53832. /**
  53833. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  53834. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  53835. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  53836. * 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`).
  53837. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  53838. * 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.
  53839. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53840. * 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).
  53841. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53842. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53843. */
  53844. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  53845. var sphere = new BABYLON.Mesh(name, scene);
  53846. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53847. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53848. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  53849. vertexData.applyToMesh(sphere, options.updatable);
  53850. return sphere;
  53851. };
  53852. ;
  53853. /**
  53854. * Creates a ribbon mesh.
  53855. * 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.
  53856. *
  53857. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  53858. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  53859. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  53860. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  53861. * 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.
  53862. * 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.
  53863. * 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
  53864. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53865. * 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).
  53866. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53867. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53868. * 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.
  53869. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  53870. * 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
  53871. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  53872. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  53873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53874. */
  53875. MeshBuilder.CreateRibbon = function (name, options, scene) {
  53876. if (scene === void 0) { scene = null; }
  53877. var pathArray = options.pathArray;
  53878. var closeArray = options.closeArray;
  53879. var closePath = options.closePath;
  53880. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53881. var instance = options.instance;
  53882. var updatable = options.updatable;
  53883. if (instance) {
  53884. // positionFunction : ribbon case
  53885. // only pathArray and sideOrientation parameters are taken into account for positions update
  53886. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  53887. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  53888. var positionFunction = function (positions) {
  53889. var minlg = pathArray[0].length;
  53890. var i = 0;
  53891. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  53892. for (var si = 1; si <= ns; si++) {
  53893. for (var p = 0; p < pathArray.length; p++) {
  53894. var path = pathArray[p];
  53895. var l = path.length;
  53896. minlg = (minlg < l) ? minlg : l;
  53897. var j = 0;
  53898. while (j < minlg) {
  53899. positions[i] = path[j].x;
  53900. positions[i + 1] = path[j].y;
  53901. positions[i + 2] = path[j].z;
  53902. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  53903. BABYLON.Tmp.Vector3[0].x = path[j].x;
  53904. }
  53905. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  53906. BABYLON.Tmp.Vector3[1].x = path[j].x;
  53907. }
  53908. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  53909. BABYLON.Tmp.Vector3[0].y = path[j].y;
  53910. }
  53911. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  53912. BABYLON.Tmp.Vector3[1].y = path[j].y;
  53913. }
  53914. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  53915. BABYLON.Tmp.Vector3[0].z = path[j].z;
  53916. }
  53917. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  53918. BABYLON.Tmp.Vector3[1].z = path[j].z;
  53919. }
  53920. j++;
  53921. i += 3;
  53922. }
  53923. if (instance._closePath) {
  53924. positions[i] = path[0].x;
  53925. positions[i + 1] = path[0].y;
  53926. positions[i + 2] = path[0].z;
  53927. i += 3;
  53928. }
  53929. }
  53930. }
  53931. };
  53932. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53933. positionFunction(positions);
  53934. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  53935. instance._boundingInfo.update(instance._worldMatrix);
  53936. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  53937. if (options.colors) {
  53938. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53939. for (var c = 0; c < options.colors.length; c++) {
  53940. colors[c * 4] = options.colors[c].r;
  53941. colors[c * 4 + 1] = options.colors[c].g;
  53942. colors[c * 4 + 2] = options.colors[c].b;
  53943. colors[c * 4 + 3] = options.colors[c].a;
  53944. }
  53945. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  53946. }
  53947. if (options.uvs) {
  53948. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53949. for (var i = 0; i < options.uvs.length; i++) {
  53950. uvs[i * 2] = options.uvs[i].x;
  53951. uvs[i * 2 + 1] = options.uvs[i].y;
  53952. }
  53953. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  53954. }
  53955. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  53956. var indices = instance.getIndices();
  53957. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53958. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  53959. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  53960. if (instance._closePath) {
  53961. var indexFirst = 0;
  53962. var indexLast = 0;
  53963. for (var p = 0; p < pathArray.length; p++) {
  53964. indexFirst = instance._idx[p] * 3;
  53965. if (p + 1 < pathArray.length) {
  53966. indexLast = (instance._idx[p + 1] - 1) * 3;
  53967. }
  53968. else {
  53969. indexLast = normals.length - 3;
  53970. }
  53971. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  53972. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  53973. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  53974. normals[indexLast] = normals[indexFirst];
  53975. normals[indexLast + 1] = normals[indexFirst + 1];
  53976. normals[indexLast + 2] = normals[indexFirst + 2];
  53977. }
  53978. }
  53979. if (!(instance.areNormalsFrozen)) {
  53980. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  53981. }
  53982. }
  53983. return instance;
  53984. }
  53985. else {
  53986. var ribbon = new BABYLON.Mesh(name, scene);
  53987. ribbon._originalBuilderSideOrientation = sideOrientation;
  53988. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  53989. if (closePath) {
  53990. ribbon._idx = vertexData._idx;
  53991. }
  53992. ribbon._closePath = closePath;
  53993. ribbon._closeArray = closeArray;
  53994. vertexData.applyToMesh(ribbon, updatable);
  53995. return ribbon;
  53996. }
  53997. };
  53998. /**
  53999. * Creates a cylinder or a cone mesh.
  54000. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  54001. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  54002. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  54003. * 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.
  54004. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  54005. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  54006. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  54007. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  54008. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  54009. * 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).
  54010. * 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
  54011. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  54012. * 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
  54013. * 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.
  54014. * If `enclose` is false, a ring surface is one element.
  54015. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  54016. * 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
  54017. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54018. * 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).
  54019. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54020. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54021. */
  54022. MeshBuilder.CreateCylinder = function (name, options, scene) {
  54023. var cylinder = new BABYLON.Mesh(name, scene);
  54024. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54025. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  54026. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  54027. vertexData.applyToMesh(cylinder, options.updatable);
  54028. return cylinder;
  54029. };
  54030. /**
  54031. * Creates a torus mesh.
  54032. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  54033. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  54034. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  54035. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  54036. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54037. * 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).
  54038. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54039. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54040. */
  54041. MeshBuilder.CreateTorus = function (name, options, scene) {
  54042. var torus = new BABYLON.Mesh(name, scene);
  54043. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54044. torus._originalBuilderSideOrientation = options.sideOrientation;
  54045. var vertexData = BABYLON.VertexData.CreateTorus(options);
  54046. vertexData.applyToMesh(torus, options.updatable);
  54047. return torus;
  54048. };
  54049. /**
  54050. * Creates a torus knot mesh.
  54051. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  54052. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  54053. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  54054. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  54055. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  54056. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54057. * 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).
  54058. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54059. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54060. */
  54061. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  54062. var torusKnot = new BABYLON.Mesh(name, scene);
  54063. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54064. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  54065. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  54066. vertexData.applyToMesh(torusKnot, options.updatable);
  54067. return torusKnot;
  54068. };
  54069. /**
  54070. * Creates a line system mesh.
  54071. * A line system is a pool of many lines gathered in a single mesh.
  54072. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  54073. * 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.
  54074. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  54075. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  54076. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  54077. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  54078. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  54079. * 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
  54080. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  54081. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54082. */
  54083. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  54084. var instance = options.instance;
  54085. var lines = options.lines;
  54086. var colors = options.colors;
  54087. if (instance) {
  54088. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54089. var vertexColor;
  54090. var lineColors;
  54091. if (colors) {
  54092. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54093. }
  54094. var i = 0;
  54095. var c = 0;
  54096. for (var l = 0; l < lines.length; l++) {
  54097. var points = lines[l];
  54098. for (var p = 0; p < points.length; p++) {
  54099. positions[i] = points[p].x;
  54100. positions[i + 1] = points[p].y;
  54101. positions[i + 2] = points[p].z;
  54102. if (colors && vertexColor) {
  54103. lineColors = colors[l];
  54104. vertexColor[c] = lineColors[p].r;
  54105. vertexColor[c + 1] = lineColors[p].g;
  54106. vertexColor[c + 2] = lineColors[p].b;
  54107. vertexColor[c + 3] = lineColors[p].a;
  54108. c += 4;
  54109. }
  54110. i += 3;
  54111. }
  54112. }
  54113. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54114. if (colors && vertexColor) {
  54115. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  54116. }
  54117. return instance;
  54118. }
  54119. // line system creation
  54120. var useVertexColor = (colors) ? true : false;
  54121. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  54122. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  54123. vertexData.applyToMesh(lineSystem, options.updatable);
  54124. return lineSystem;
  54125. };
  54126. /**
  54127. * Creates a line mesh.
  54128. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  54129. * 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.
  54130. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54131. * The parameter `points` is an array successive Vector3.
  54132. * 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
  54133. * The optional parameter `colors` is an array of successive Color4, one per line point.
  54134. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  54135. * When updating an instance, remember that only point positions can change, not the number of points.
  54136. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54137. */
  54138. MeshBuilder.CreateLines = function (name, options, scene) {
  54139. if (scene === void 0) { scene = null; }
  54140. var colors = (options.colors) ? [options.colors] : null;
  54141. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  54142. return lines;
  54143. };
  54144. /**
  54145. * Creates a dashed line mesh.
  54146. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  54147. * 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.
  54148. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54149. * The parameter `points` is an array successive Vector3.
  54150. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  54151. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  54152. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  54153. * 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
  54154. * When updating an instance, remember that only point positions can change, not the number of points.
  54155. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54156. */
  54157. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  54158. if (scene === void 0) { scene = null; }
  54159. var points = options.points;
  54160. var instance = options.instance;
  54161. var gapSize = options.gapSize || 1;
  54162. var dashSize = options.dashSize || 3;
  54163. if (instance) {
  54164. var positionFunction = function (positions) {
  54165. var curvect = BABYLON.Vector3.Zero();
  54166. var nbSeg = positions.length / 6;
  54167. var lg = 0;
  54168. var nb = 0;
  54169. var shft = 0;
  54170. var dashshft = 0;
  54171. var curshft = 0;
  54172. var p = 0;
  54173. var i = 0;
  54174. var j = 0;
  54175. for (i = 0; i < points.length - 1; i++) {
  54176. points[i + 1].subtractToRef(points[i], curvect);
  54177. lg += curvect.length();
  54178. }
  54179. shft = lg / nbSeg;
  54180. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  54181. for (i = 0; i < points.length - 1; i++) {
  54182. points[i + 1].subtractToRef(points[i], curvect);
  54183. nb = Math.floor(curvect.length() / shft);
  54184. curvect.normalize();
  54185. j = 0;
  54186. while (j < nb && p < positions.length) {
  54187. curshft = shft * j;
  54188. positions[p] = points[i].x + curshft * curvect.x;
  54189. positions[p + 1] = points[i].y + curshft * curvect.y;
  54190. positions[p + 2] = points[i].z + curshft * curvect.z;
  54191. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  54192. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  54193. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  54194. p += 6;
  54195. j++;
  54196. }
  54197. }
  54198. while (p < positions.length) {
  54199. positions[p] = points[i].x;
  54200. positions[p + 1] = points[i].y;
  54201. positions[p + 2] = points[i].z;
  54202. p += 3;
  54203. }
  54204. };
  54205. instance.updateMeshPositions(positionFunction, false);
  54206. return instance;
  54207. }
  54208. // dashed lines creation
  54209. var dashedLines = new BABYLON.LinesMesh(name, scene);
  54210. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  54211. vertexData.applyToMesh(dashedLines, options.updatable);
  54212. dashedLines.dashSize = dashSize;
  54213. dashedLines.gapSize = gapSize;
  54214. return dashedLines;
  54215. };
  54216. /**
  54217. * Creates an extruded shape mesh.
  54218. * 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.
  54219. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  54220. *
  54221. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54222. * 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
  54223. * extruded along the Z axis.
  54224. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54225. * 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.
  54226. * The parameter `scale` (float, default 1) is the value to scale the shape.
  54227. * 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
  54228. * 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
  54229. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54230. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54231. * 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).
  54232. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54233. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54234. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54235. */
  54236. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  54237. if (scene === void 0) { scene = null; }
  54238. var path = options.path;
  54239. var shape = options.shape;
  54240. var scale = options.scale || 1;
  54241. var rotation = options.rotation || 0;
  54242. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54243. var updatable = options.updatable;
  54244. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54245. var instance = options.instance || null;
  54246. var invertUV = options.invertUV || false;
  54247. 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);
  54248. };
  54249. /**
  54250. * Creates an custom extruded shape mesh.
  54251. * 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.
  54252. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  54253. *
  54254. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54255. * 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
  54256. * extruded along the Z axis.
  54257. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54258. * 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
  54259. * and the distance of this point from the begining of the path :
  54260. * ```javascript
  54261. * var rotationFunction = function(i, distance) {
  54262. * // do things
  54263. * return rotationValue; }
  54264. * ```
  54265. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  54266. * 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
  54267. * and the distance of this point from the begining of the path :
  54268. * ```javascript
  54269. * var scaleFunction = function(i, distance) {
  54270. * // do things
  54271. * return scaleValue;}
  54272. * ```
  54273. * It must returns a float value that will be the scale value applied to the shape on each path point.
  54274. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  54275. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  54276. * 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
  54277. * 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
  54278. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54279. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54280. * 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).
  54281. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54282. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54284. */
  54285. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  54286. var path = options.path;
  54287. var shape = options.shape;
  54288. var scaleFunction = options.scaleFunction || (function () { return 1; });
  54289. var rotationFunction = options.rotationFunction || (function () { return 0; });
  54290. var ribbonCloseArray = options.ribbonCloseArray || false;
  54291. var ribbonClosePath = options.ribbonClosePath || false;
  54292. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54293. var updatable = options.updatable;
  54294. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54295. var instance = options.instance;
  54296. var invertUV = options.invertUV || false;
  54297. 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);
  54298. };
  54299. /**
  54300. * Creates lathe mesh.
  54301. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  54302. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  54303. *
  54304. * 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
  54305. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  54306. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  54307. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  54308. * 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.
  54309. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  54310. * 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
  54311. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54312. * 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).
  54313. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54314. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54315. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54316. */
  54317. MeshBuilder.CreateLathe = function (name, options, scene) {
  54318. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  54319. var closed = (options.closed === undefined) ? true : options.closed;
  54320. var shape = options.shape;
  54321. var radius = options.radius || 1;
  54322. var tessellation = options.tessellation || 64;
  54323. var updatable = options.updatable;
  54324. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54325. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54326. var pi2 = Math.PI * 2;
  54327. var paths = new Array();
  54328. var invertUV = options.invertUV || false;
  54329. var i = 0;
  54330. var p = 0;
  54331. var step = pi2 / tessellation * arc;
  54332. var rotated;
  54333. var path = new Array();
  54334. ;
  54335. for (i = 0; i <= tessellation; i++) {
  54336. var path = [];
  54337. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  54338. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  54339. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  54340. }
  54341. for (p = 0; p < shape.length; p++) {
  54342. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  54343. path.push(rotated);
  54344. }
  54345. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  54346. 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));
  54347. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  54348. }
  54349. paths.push(path);
  54350. }
  54351. // lathe ribbon
  54352. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54353. return lathe;
  54354. };
  54355. /**
  54356. * Creates a plane mesh.
  54357. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54358. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  54359. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  54360. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  54361. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54362. * 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).
  54363. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54364. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54365. */
  54366. MeshBuilder.CreatePlane = function (name, options, scene) {
  54367. var plane = new BABYLON.Mesh(name, scene);
  54368. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54369. plane._originalBuilderSideOrientation = options.sideOrientation;
  54370. var vertexData = BABYLON.VertexData.CreatePlane(options);
  54371. vertexData.applyToMesh(plane, options.updatable);
  54372. if (options.sourcePlane) {
  54373. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  54374. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  54375. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  54376. plane.rotate(vectorProduct, product);
  54377. }
  54378. return plane;
  54379. };
  54380. /**
  54381. * Creates a ground mesh.
  54382. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54383. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  54384. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  54385. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54386. */
  54387. MeshBuilder.CreateGround = function (name, options, scene) {
  54388. var ground = new BABYLON.GroundMesh(name, scene);
  54389. ground._setReady(false);
  54390. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  54391. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  54392. ground._width = options.width || 1;
  54393. ground._height = options.height || 1;
  54394. ground._maxX = ground._width / 2;
  54395. ground._maxZ = ground._height / 2;
  54396. ground._minX = -ground._maxX;
  54397. ground._minZ = -ground._maxZ;
  54398. var vertexData = BABYLON.VertexData.CreateGround(options);
  54399. vertexData.applyToMesh(ground, options.updatable);
  54400. ground._setReady(true);
  54401. return ground;
  54402. };
  54403. /**
  54404. * Creates a tiled ground mesh.
  54405. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  54406. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  54407. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  54408. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  54409. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  54410. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  54411. * numbers of subdivisions on the ground width and height of each tile.
  54412. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54413. */
  54414. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  54415. var tiledGround = new BABYLON.Mesh(name, scene);
  54416. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  54417. vertexData.applyToMesh(tiledGround, options.updatable);
  54418. return tiledGround;
  54419. };
  54420. /**
  54421. * Creates a ground mesh from a height map.
  54422. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  54423. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  54424. * The parameter `url` sets the URL of the height map image resource.
  54425. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  54426. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  54427. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  54428. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  54429. * 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.
  54430. * 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).
  54431. * This function is passed the newly built mesh :
  54432. * ```javascript
  54433. * function(mesh) { // do things
  54434. * return; }
  54435. * ```
  54436. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54437. */
  54438. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  54439. var width = options.width || 10.0;
  54440. var height = options.height || 10.0;
  54441. var subdivisions = options.subdivisions || 1 | 0;
  54442. var minHeight = options.minHeight || 0.0;
  54443. var maxHeight = options.maxHeight || 1.0;
  54444. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  54445. var updatable = options.updatable;
  54446. var onReady = options.onReady;
  54447. var ground = new BABYLON.GroundMesh(name, scene);
  54448. ground._subdivisionsX = subdivisions;
  54449. ground._subdivisionsY = subdivisions;
  54450. ground._width = width;
  54451. ground._height = height;
  54452. ground._maxX = ground._width / 2.0;
  54453. ground._maxZ = ground._height / 2.0;
  54454. ground._minX = -ground._maxX;
  54455. ground._minZ = -ground._maxZ;
  54456. ground._setReady(false);
  54457. var onload = function (img) {
  54458. // Getting height map data
  54459. var canvas = document.createElement("canvas");
  54460. var context = canvas.getContext("2d");
  54461. if (!context) {
  54462. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  54463. }
  54464. if (scene.isDisposed) {
  54465. return;
  54466. }
  54467. var bufferWidth = img.width;
  54468. var bufferHeight = img.height;
  54469. canvas.width = bufferWidth;
  54470. canvas.height = bufferHeight;
  54471. context.drawImage(img, 0, 0);
  54472. // Create VertexData from map data
  54473. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  54474. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  54475. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  54476. width: width, height: height,
  54477. subdivisions: subdivisions,
  54478. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  54479. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  54480. });
  54481. vertexData.applyToMesh(ground, updatable);
  54482. ground._setReady(true);
  54483. //execute ready callback, if set
  54484. if (onReady) {
  54485. onReady(ground);
  54486. }
  54487. };
  54488. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  54489. return ground;
  54490. };
  54491. /**
  54492. * Creates a polygon mesh.
  54493. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  54494. * 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.
  54495. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54497. * 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).
  54498. * Remember you can only change the shape positions, not their number when updating a polygon.
  54499. */
  54500. MeshBuilder.CreatePolygon = function (name, options, scene) {
  54501. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54502. var shape = options.shape;
  54503. var holes = options.holes || [];
  54504. var depth = options.depth || 0;
  54505. var contours = [];
  54506. var hole = [];
  54507. for (var i = 0; i < shape.length; i++) {
  54508. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  54509. }
  54510. var epsilon = 0.00000001;
  54511. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  54512. contours.pop();
  54513. }
  54514. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  54515. for (var hNb = 0; hNb < holes.length; hNb++) {
  54516. hole = [];
  54517. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  54518. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  54519. }
  54520. polygonTriangulation.addHole(hole);
  54521. }
  54522. var polygon = polygonTriangulation.build(options.updatable, depth);
  54523. polygon._originalBuilderSideOrientation = options.sideOrientation;
  54524. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  54525. vertexData.applyToMesh(polygon, options.updatable);
  54526. return polygon;
  54527. };
  54528. ;
  54529. /**
  54530. * Creates an extruded polygon mesh, with depth in the Y direction.
  54531. * 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).
  54532. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54533. */
  54534. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  54535. return MeshBuilder.CreatePolygon(name, options, scene);
  54536. };
  54537. ;
  54538. /**
  54539. * Creates a tube mesh.
  54540. * 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.
  54541. *
  54542. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  54543. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  54544. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  54545. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  54546. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  54547. * 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.
  54548. * It must return a radius value (positive float) :
  54549. * ```javascript
  54550. * var radiusFunction = function(i, distance) {
  54551. * // do things
  54552. * return radius; }
  54553. * ```
  54554. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  54555. * 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
  54556. * 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
  54557. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54558. * 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).
  54559. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54560. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54562. */
  54563. MeshBuilder.CreateTube = function (name, options, scene) {
  54564. var path = options.path;
  54565. var instance = options.instance;
  54566. var radius = 1.0;
  54567. if (instance) {
  54568. radius = instance.radius;
  54569. }
  54570. if (options.radius !== undefined) {
  54571. radius = options.radius;
  54572. }
  54573. ;
  54574. var tessellation = options.tessellation || 64 | 0;
  54575. var radiusFunction = options.radiusFunction || null;
  54576. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54577. var invertUV = options.invertUV || false;
  54578. var updatable = options.updatable;
  54579. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54580. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  54581. // tube geometry
  54582. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  54583. var tangents = path3D.getTangents();
  54584. var normals = path3D.getNormals();
  54585. var distances = path3D.getDistances();
  54586. var pi2 = Math.PI * 2;
  54587. var step = pi2 / tessellation * arc;
  54588. var returnRadius = function () { return radius; };
  54589. var radiusFunctionFinal = radiusFunction || returnRadius;
  54590. var circlePath;
  54591. var rad;
  54592. var normal;
  54593. var rotated;
  54594. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54595. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54596. for (var i = 0; i < path.length; i++) {
  54597. rad = radiusFunctionFinal(i, distances[i]); // current radius
  54598. circlePath = Array(); // current circle array
  54599. normal = normals[i]; // current normal
  54600. for (var t = 0; t < tessellation; t++) {
  54601. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  54602. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  54603. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  54604. rotated.scaleInPlace(rad).addInPlace(path[i]);
  54605. circlePath[t] = rotated;
  54606. }
  54607. circlePaths[index] = circlePath;
  54608. index++;
  54609. }
  54610. // cap
  54611. var capPath = function (nbPoints, pathIndex) {
  54612. var pointCap = Array();
  54613. for (var i = 0; i < nbPoints; i++) {
  54614. pointCap.push(path[pathIndex]);
  54615. }
  54616. return pointCap;
  54617. };
  54618. switch (cap) {
  54619. case BABYLON.Mesh.NO_CAP:
  54620. break;
  54621. case BABYLON.Mesh.CAP_START:
  54622. circlePaths[0] = capPath(tessellation, 0);
  54623. circlePaths[1] = circlePaths[2].slice(0);
  54624. break;
  54625. case BABYLON.Mesh.CAP_END:
  54626. circlePaths[index] = circlePaths[index - 1].slice(0);
  54627. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54628. break;
  54629. case BABYLON.Mesh.CAP_ALL:
  54630. circlePaths[0] = capPath(tessellation, 0);
  54631. circlePaths[1] = circlePaths[2].slice(0);
  54632. circlePaths[index] = circlePaths[index - 1].slice(0);
  54633. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54634. break;
  54635. default:
  54636. break;
  54637. }
  54638. return circlePaths;
  54639. };
  54640. var path3D;
  54641. var pathArray;
  54642. if (instance) {
  54643. var arc = options.arc || instance.arc;
  54644. path3D = (instance.path3D).update(path);
  54645. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  54646. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  54647. instance.path3D = path3D;
  54648. instance.pathArray = pathArray;
  54649. instance.arc = arc;
  54650. instance.radius = radius;
  54651. return instance;
  54652. }
  54653. // tube creation
  54654. path3D = new BABYLON.Path3D(path);
  54655. var newPathArray = new Array();
  54656. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54657. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  54658. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54659. tube.pathArray = pathArray;
  54660. tube.path3D = path3D;
  54661. tube.tessellation = tessellation;
  54662. tube.cap = cap;
  54663. tube.arc = options.arc;
  54664. tube.radius = radius;
  54665. return tube;
  54666. };
  54667. /**
  54668. * Creates a polyhedron mesh.
  54669. *
  54670. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  54671. * 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
  54672. * to choose the wanted type.
  54673. * The parameter `size` (positive float, default 1) sets the polygon size.
  54674. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  54675. * 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`.
  54676. * 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
  54677. * 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)`).
  54678. * 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
  54679. * 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.
  54680. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54681. * 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).
  54682. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54683. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54684. */
  54685. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  54686. var polyhedron = new BABYLON.Mesh(name, scene);
  54687. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54688. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  54689. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  54690. vertexData.applyToMesh(polyhedron, options.updatable);
  54691. return polyhedron;
  54692. };
  54693. /**
  54694. * Creates a decal mesh.
  54695. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  54696. * 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.
  54697. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  54698. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  54699. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  54700. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  54701. */
  54702. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  54703. var indices = sourceMesh.getIndices();
  54704. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54705. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54706. var position = options.position || BABYLON.Vector3.Zero();
  54707. var normal = options.normal || BABYLON.Vector3.Up();
  54708. var size = options.size || BABYLON.Vector3.One();
  54709. var angle = options.angle || 0;
  54710. // Getting correct rotation
  54711. if (!normal) {
  54712. var target = new BABYLON.Vector3(0, 0, 1);
  54713. var camera = sourceMesh.getScene().activeCamera;
  54714. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  54715. normal = camera.globalPosition.subtract(cameraWorldTarget);
  54716. }
  54717. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  54718. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  54719. var pitch = Math.atan2(normal.y, len);
  54720. // Matrix
  54721. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  54722. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  54723. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  54724. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  54725. var vertexData = new BABYLON.VertexData();
  54726. vertexData.indices = [];
  54727. vertexData.positions = [];
  54728. vertexData.normals = [];
  54729. vertexData.uvs = [];
  54730. var currentVertexDataIndex = 0;
  54731. var extractDecalVector3 = function (indexId) {
  54732. var result = new BABYLON.PositionNormalVertex();
  54733. if (!indices || !positions || !normals) {
  54734. return result;
  54735. }
  54736. var vertexId = indices[indexId];
  54737. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  54738. // Send vector to decal local world
  54739. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  54740. // Get normal
  54741. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  54742. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  54743. return result;
  54744. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  54745. var clip = function (vertices, axis) {
  54746. if (vertices.length === 0) {
  54747. return vertices;
  54748. }
  54749. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  54750. var clipVertices = function (v0, v1) {
  54751. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  54752. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  54753. };
  54754. var result = new Array();
  54755. for (var index = 0; index < vertices.length; index += 3) {
  54756. var v1Out;
  54757. var v2Out;
  54758. var v3Out;
  54759. var total = 0;
  54760. var nV1 = null;
  54761. var nV2 = null;
  54762. var nV3 = null;
  54763. var nV4 = null;
  54764. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  54765. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  54766. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  54767. v1Out = d1 > 0;
  54768. v2Out = d2 > 0;
  54769. v3Out = d3 > 0;
  54770. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  54771. switch (total) {
  54772. case 0:
  54773. result.push(vertices[index]);
  54774. result.push(vertices[index + 1]);
  54775. result.push(vertices[index + 2]);
  54776. break;
  54777. case 1:
  54778. if (v1Out) {
  54779. nV1 = vertices[index + 1];
  54780. nV2 = vertices[index + 2];
  54781. nV3 = clipVertices(vertices[index], nV1);
  54782. nV4 = clipVertices(vertices[index], nV2);
  54783. }
  54784. if (v2Out) {
  54785. nV1 = vertices[index];
  54786. nV2 = vertices[index + 2];
  54787. nV3 = clipVertices(vertices[index + 1], nV1);
  54788. nV4 = clipVertices(vertices[index + 1], nV2);
  54789. result.push(nV3);
  54790. result.push(nV2.clone());
  54791. result.push(nV1.clone());
  54792. result.push(nV2.clone());
  54793. result.push(nV3.clone());
  54794. result.push(nV4);
  54795. break;
  54796. }
  54797. if (v3Out) {
  54798. nV1 = vertices[index];
  54799. nV2 = vertices[index + 1];
  54800. nV3 = clipVertices(vertices[index + 2], nV1);
  54801. nV4 = clipVertices(vertices[index + 2], nV2);
  54802. }
  54803. if (nV1 && nV2 && nV3 && nV4) {
  54804. result.push(nV1.clone());
  54805. result.push(nV2.clone());
  54806. result.push(nV3);
  54807. result.push(nV4);
  54808. result.push(nV3.clone());
  54809. result.push(nV2.clone());
  54810. }
  54811. break;
  54812. case 2:
  54813. if (!v1Out) {
  54814. nV1 = vertices[index].clone();
  54815. nV2 = clipVertices(nV1, vertices[index + 1]);
  54816. nV3 = clipVertices(nV1, vertices[index + 2]);
  54817. result.push(nV1);
  54818. result.push(nV2);
  54819. result.push(nV3);
  54820. }
  54821. if (!v2Out) {
  54822. nV1 = vertices[index + 1].clone();
  54823. nV2 = clipVertices(nV1, vertices[index + 2]);
  54824. nV3 = clipVertices(nV1, vertices[index]);
  54825. result.push(nV1);
  54826. result.push(nV2);
  54827. result.push(nV3);
  54828. }
  54829. if (!v3Out) {
  54830. nV1 = vertices[index + 2].clone();
  54831. nV2 = clipVertices(nV1, vertices[index]);
  54832. nV3 = clipVertices(nV1, vertices[index + 1]);
  54833. result.push(nV1);
  54834. result.push(nV2);
  54835. result.push(nV3);
  54836. }
  54837. break;
  54838. case 3:
  54839. break;
  54840. }
  54841. }
  54842. return result;
  54843. };
  54844. for (var index = 0; index < indices.length; index += 3) {
  54845. var faceVertices = new Array();
  54846. faceVertices.push(extractDecalVector3(index));
  54847. faceVertices.push(extractDecalVector3(index + 1));
  54848. faceVertices.push(extractDecalVector3(index + 2));
  54849. // Clip
  54850. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  54851. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  54852. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  54853. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  54854. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  54855. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  54856. if (faceVertices.length === 0) {
  54857. continue;
  54858. }
  54859. // Add UVs and get back to world
  54860. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  54861. var vertex = faceVertices[vIndex];
  54862. //TODO check for Int32Array | Uint32Array | Uint16Array
  54863. vertexData.indices.push(currentVertexDataIndex);
  54864. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  54865. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  54866. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  54867. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  54868. currentVertexDataIndex++;
  54869. }
  54870. }
  54871. // Return mesh
  54872. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  54873. vertexData.applyToMesh(decal);
  54874. decal.position = position.clone();
  54875. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  54876. return decal;
  54877. };
  54878. // Privates
  54879. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  54880. // extrusion geometry
  54881. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  54882. var tangents = path3D.getTangents();
  54883. var normals = path3D.getNormals();
  54884. var binormals = path3D.getBinormals();
  54885. var distances = path3D.getDistances();
  54886. var angle = 0;
  54887. var returnScale = function () { return scale !== null ? scale : 1; };
  54888. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  54889. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  54890. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  54891. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54892. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54893. for (var i = 0; i < curve.length; i++) {
  54894. var shapePath = new Array();
  54895. var angleStep = rotate(i, distances[i]);
  54896. var scaleRatio = scl(i, distances[i]);
  54897. for (var p = 0; p < shape.length; p++) {
  54898. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  54899. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  54900. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  54901. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  54902. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  54903. shapePath[p] = rotated;
  54904. }
  54905. shapePaths[index] = shapePath;
  54906. angle += angleStep;
  54907. index++;
  54908. }
  54909. // cap
  54910. var capPath = function (shapePath) {
  54911. var pointCap = Array();
  54912. var barycenter = BABYLON.Vector3.Zero();
  54913. var i;
  54914. for (i = 0; i < shapePath.length; i++) {
  54915. barycenter.addInPlace(shapePath[i]);
  54916. }
  54917. barycenter.scaleInPlace(1.0 / shapePath.length);
  54918. for (i = 0; i < shapePath.length; i++) {
  54919. pointCap.push(barycenter);
  54920. }
  54921. return pointCap;
  54922. };
  54923. switch (cap) {
  54924. case BABYLON.Mesh.NO_CAP:
  54925. break;
  54926. case BABYLON.Mesh.CAP_START:
  54927. shapePaths[0] = capPath(shapePaths[2]);
  54928. shapePaths[1] = shapePaths[2];
  54929. break;
  54930. case BABYLON.Mesh.CAP_END:
  54931. shapePaths[index] = shapePaths[index - 1];
  54932. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54933. break;
  54934. case BABYLON.Mesh.CAP_ALL:
  54935. shapePaths[0] = capPath(shapePaths[2]);
  54936. shapePaths[1] = shapePaths[2];
  54937. shapePaths[index] = shapePaths[index - 1];
  54938. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54939. break;
  54940. default:
  54941. break;
  54942. }
  54943. return shapePaths;
  54944. };
  54945. var path3D;
  54946. var pathArray;
  54947. if (instance) {
  54948. path3D = (instance.path3D).update(curve);
  54949. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  54950. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  54951. return instance;
  54952. }
  54953. // extruded shape creation
  54954. path3D = new BABYLON.Path3D(curve);
  54955. var newShapePaths = new Array();
  54956. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54957. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  54958. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  54959. extrudedGeneric.pathArray = pathArray;
  54960. extrudedGeneric.path3D = path3D;
  54961. extrudedGeneric.cap = cap;
  54962. return extrudedGeneric;
  54963. };
  54964. return MeshBuilder;
  54965. }());
  54966. BABYLON.MeshBuilder = MeshBuilder;
  54967. })(BABYLON || (BABYLON = {}));
  54968. //# sourceMappingURL=babylon.meshBuilder.js.map
  54969. var BABYLON;
  54970. (function (BABYLON) {
  54971. var AudioEngine = /** @class */ (function () {
  54972. function AudioEngine() {
  54973. this._audioContext = null;
  54974. this._audioContextInitialized = false;
  54975. this.canUseWebAudio = false;
  54976. this.WarnedWebAudioUnsupported = false;
  54977. this.unlocked = false;
  54978. this.isMP3supported = false;
  54979. this.isOGGsupported = false;
  54980. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  54981. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  54982. this.canUseWebAudio = true;
  54983. }
  54984. var audioElem = document.createElement('audio');
  54985. try {
  54986. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  54987. this.isMP3supported = true;
  54988. }
  54989. }
  54990. catch (e) {
  54991. // protect error during capability check.
  54992. }
  54993. try {
  54994. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  54995. this.isOGGsupported = true;
  54996. }
  54997. }
  54998. catch (e) {
  54999. // protect error during capability check.
  55000. }
  55001. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  55002. this._unlockiOSaudio();
  55003. }
  55004. else {
  55005. this.unlocked = true;
  55006. }
  55007. }
  55008. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  55009. get: function () {
  55010. if (!this._audioContextInitialized) {
  55011. this._initializeAudioContext();
  55012. }
  55013. return this._audioContext;
  55014. },
  55015. enumerable: true,
  55016. configurable: true
  55017. });
  55018. AudioEngine.prototype._unlockiOSaudio = function () {
  55019. var _this = this;
  55020. var unlockaudio = function () {
  55021. if (!_this.audioContext) {
  55022. return;
  55023. }
  55024. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  55025. var source = _this.audioContext.createBufferSource();
  55026. source.buffer = buffer;
  55027. source.connect(_this.audioContext.destination);
  55028. source.start(0);
  55029. setTimeout(function () {
  55030. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  55031. _this.unlocked = true;
  55032. window.removeEventListener('touchend', unlockaudio, false);
  55033. if (_this.onAudioUnlocked) {
  55034. _this.onAudioUnlocked();
  55035. }
  55036. }
  55037. }, 0);
  55038. };
  55039. window.addEventListener('touchend', unlockaudio, false);
  55040. };
  55041. AudioEngine.prototype._initializeAudioContext = function () {
  55042. try {
  55043. if (this.canUseWebAudio) {
  55044. this._audioContext = new AudioContext();
  55045. // create a global volume gain node
  55046. this.masterGain = this._audioContext.createGain();
  55047. this.masterGain.gain.value = 1;
  55048. this.masterGain.connect(this._audioContext.destination);
  55049. this._audioContextInitialized = true;
  55050. }
  55051. }
  55052. catch (e) {
  55053. this.canUseWebAudio = false;
  55054. BABYLON.Tools.Error("Web Audio: " + e.message);
  55055. }
  55056. };
  55057. AudioEngine.prototype.dispose = function () {
  55058. if (this.canUseWebAudio && this._audioContextInitialized) {
  55059. if (this._connectedAnalyser && this._audioContext) {
  55060. this._connectedAnalyser.stopDebugCanvas();
  55061. this._connectedAnalyser.dispose();
  55062. this.masterGain.disconnect();
  55063. this.masterGain.connect(this._audioContext.destination);
  55064. this._connectedAnalyser = null;
  55065. }
  55066. this.masterGain.gain.value = 1;
  55067. }
  55068. this.WarnedWebAudioUnsupported = false;
  55069. };
  55070. AudioEngine.prototype.getGlobalVolume = function () {
  55071. if (this.canUseWebAudio && this._audioContextInitialized) {
  55072. return this.masterGain.gain.value;
  55073. }
  55074. else {
  55075. return -1;
  55076. }
  55077. };
  55078. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  55079. if (this.canUseWebAudio && this._audioContextInitialized) {
  55080. this.masterGain.gain.value = newVolume;
  55081. }
  55082. };
  55083. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  55084. if (this._connectedAnalyser) {
  55085. this._connectedAnalyser.stopDebugCanvas();
  55086. }
  55087. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  55088. this._connectedAnalyser = analyser;
  55089. this.masterGain.disconnect();
  55090. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  55091. }
  55092. };
  55093. return AudioEngine;
  55094. }());
  55095. BABYLON.AudioEngine = AudioEngine;
  55096. })(BABYLON || (BABYLON = {}));
  55097. //# sourceMappingURL=babylon.audioEngine.js.map
  55098. var BABYLON;
  55099. (function (BABYLON) {
  55100. var Sound = /** @class */ (function () {
  55101. /**
  55102. * Create a sound and attach it to a scene
  55103. * @param name Name of your sound
  55104. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  55105. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  55106. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  55107. */
  55108. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  55109. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  55110. var _this = this;
  55111. this.autoplay = false;
  55112. this.loop = false;
  55113. this.useCustomAttenuation = false;
  55114. this.spatialSound = false;
  55115. this.refDistance = 1;
  55116. this.rolloffFactor = 1;
  55117. this.maxDistance = 100;
  55118. this.distanceModel = "linear";
  55119. this._panningModel = "equalpower";
  55120. this._playbackRate = 1;
  55121. this._streaming = false;
  55122. this._startTime = 0;
  55123. this._startOffset = 0;
  55124. this._position = BABYLON.Vector3.Zero();
  55125. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  55126. this._volume = 1;
  55127. this._isReadyToPlay = false;
  55128. this.isPlaying = false;
  55129. this.isPaused = false;
  55130. this._isDirectional = false;
  55131. // Used if you'd like to create a directional sound.
  55132. // If not set, the sound will be omnidirectional
  55133. this._coneInnerAngle = 360;
  55134. this._coneOuterAngle = 360;
  55135. this._coneOuterGain = 0;
  55136. this._isOutputConnected = false;
  55137. this._urlType = "Unknown";
  55138. this.name = name;
  55139. this._scene = scene;
  55140. this._readyToPlayCallback = readyToPlayCallback;
  55141. // Default custom attenuation function is a linear attenuation
  55142. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  55143. if (currentDistance < maxDistance) {
  55144. return currentVolume * (1 - currentDistance / maxDistance);
  55145. }
  55146. else {
  55147. return 0;
  55148. }
  55149. };
  55150. if (options) {
  55151. this.autoplay = options.autoplay || false;
  55152. this.loop = options.loop || false;
  55153. // if volume === 0, we need another way to check this option
  55154. if (options.volume !== undefined) {
  55155. this._volume = options.volume;
  55156. }
  55157. this.spatialSound = options.spatialSound || false;
  55158. this.maxDistance = options.maxDistance || 100;
  55159. this.useCustomAttenuation = options.useCustomAttenuation || false;
  55160. this.rolloffFactor = options.rolloffFactor || 1;
  55161. this.refDistance = options.refDistance || 1;
  55162. this.distanceModel = options.distanceModel || "linear";
  55163. this._playbackRate = options.playbackRate || 1;
  55164. this._streaming = options.streaming || false;
  55165. }
  55166. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55167. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  55168. this._soundGain.gain.value = this._volume;
  55169. this._inputAudioNode = this._soundGain;
  55170. this._ouputAudioNode = this._soundGain;
  55171. if (this.spatialSound) {
  55172. this._createSpatialParameters();
  55173. }
  55174. this._scene.mainSoundTrack.AddSound(this);
  55175. var validParameter = true;
  55176. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  55177. if (urlOrArrayBuffer) {
  55178. if (typeof (urlOrArrayBuffer) === "string")
  55179. this._urlType = "String";
  55180. if (Array.isArray(urlOrArrayBuffer))
  55181. this._urlType = "Array";
  55182. if (urlOrArrayBuffer instanceof ArrayBuffer)
  55183. this._urlType = "ArrayBuffer";
  55184. var urls = [];
  55185. var codecSupportedFound = false;
  55186. switch (this._urlType) {
  55187. case "ArrayBuffer":
  55188. if (urlOrArrayBuffer.byteLength > 0) {
  55189. codecSupportedFound = true;
  55190. this._soundLoaded(urlOrArrayBuffer);
  55191. }
  55192. break;
  55193. case "String":
  55194. urls.push(urlOrArrayBuffer);
  55195. case "Array":
  55196. if (urls.length === 0)
  55197. urls = urlOrArrayBuffer;
  55198. // If we found a supported format, we load it immediately and stop the loop
  55199. for (var i = 0; i < urls.length; i++) {
  55200. var url = urls[i];
  55201. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  55202. codecSupportedFound = true;
  55203. }
  55204. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  55205. codecSupportedFound = true;
  55206. }
  55207. if (url.indexOf(".wav", url.length - 4) !== -1) {
  55208. codecSupportedFound = true;
  55209. }
  55210. if (url.indexOf("blob:") !== -1) {
  55211. codecSupportedFound = true;
  55212. }
  55213. if (codecSupportedFound) {
  55214. // Loading sound using XHR2
  55215. if (!this._streaming) {
  55216. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  55217. }
  55218. else {
  55219. this._htmlAudioElement = new Audio(url);
  55220. this._htmlAudioElement.controls = false;
  55221. this._htmlAudioElement.loop = this.loop;
  55222. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  55223. this._htmlAudioElement.preload = "auto";
  55224. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  55225. _this._isReadyToPlay = true;
  55226. if (_this.autoplay) {
  55227. _this.play();
  55228. }
  55229. if (_this._readyToPlayCallback) {
  55230. _this._readyToPlayCallback();
  55231. }
  55232. });
  55233. document.body.appendChild(this._htmlAudioElement);
  55234. }
  55235. break;
  55236. }
  55237. }
  55238. break;
  55239. default:
  55240. validParameter = false;
  55241. break;
  55242. }
  55243. if (!validParameter) {
  55244. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  55245. }
  55246. else {
  55247. if (!codecSupportedFound) {
  55248. this._isReadyToPlay = true;
  55249. // Simulating a ready to play event to avoid breaking code path
  55250. if (this._readyToPlayCallback) {
  55251. window.setTimeout(function () {
  55252. if (_this._readyToPlayCallback) {
  55253. _this._readyToPlayCallback();
  55254. }
  55255. }, 1000);
  55256. }
  55257. }
  55258. }
  55259. }
  55260. }
  55261. else {
  55262. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  55263. this._scene.mainSoundTrack.AddSound(this);
  55264. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  55265. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  55266. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  55267. }
  55268. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  55269. if (this._readyToPlayCallback) {
  55270. window.setTimeout(function () {
  55271. if (_this._readyToPlayCallback) {
  55272. _this._readyToPlayCallback();
  55273. }
  55274. }, 1000);
  55275. }
  55276. }
  55277. }
  55278. Sound.prototype.dispose = function () {
  55279. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  55280. if (this.isPlaying) {
  55281. this.stop();
  55282. }
  55283. this._isReadyToPlay = false;
  55284. if (this.soundTrackId === -1) {
  55285. this._scene.mainSoundTrack.RemoveSound(this);
  55286. }
  55287. else {
  55288. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  55289. }
  55290. if (this._soundGain) {
  55291. this._soundGain.disconnect();
  55292. this._soundGain = null;
  55293. }
  55294. if (this._soundPanner) {
  55295. this._soundPanner.disconnect();
  55296. this._soundPanner = null;
  55297. }
  55298. if (this._soundSource) {
  55299. this._soundSource.disconnect();
  55300. this._soundSource = null;
  55301. }
  55302. this._audioBuffer = null;
  55303. if (this._htmlAudioElement) {
  55304. this._htmlAudioElement.pause();
  55305. this._htmlAudioElement.src = "";
  55306. document.body.removeChild(this._htmlAudioElement);
  55307. }
  55308. if (this._connectedMesh && this._registerFunc) {
  55309. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55310. this._connectedMesh = null;
  55311. }
  55312. }
  55313. };
  55314. Sound.prototype.isReady = function () {
  55315. return this._isReadyToPlay;
  55316. };
  55317. Sound.prototype._soundLoaded = function (audioData) {
  55318. var _this = this;
  55319. if (!BABYLON.Engine.audioEngine.audioContext) {
  55320. return;
  55321. }
  55322. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  55323. _this._audioBuffer = buffer;
  55324. _this._isReadyToPlay = true;
  55325. if (_this.autoplay) {
  55326. _this.play();
  55327. }
  55328. if (_this._readyToPlayCallback) {
  55329. _this._readyToPlayCallback();
  55330. }
  55331. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  55332. };
  55333. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  55334. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55335. this._audioBuffer = audioBuffer;
  55336. this._isReadyToPlay = true;
  55337. }
  55338. };
  55339. Sound.prototype.updateOptions = function (options) {
  55340. if (options) {
  55341. this.loop = options.loop || this.loop;
  55342. this.maxDistance = options.maxDistance || this.maxDistance;
  55343. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  55344. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  55345. this.refDistance = options.refDistance || this.refDistance;
  55346. this.distanceModel = options.distanceModel || this.distanceModel;
  55347. this._playbackRate = options.playbackRate || this._playbackRate;
  55348. this._updateSpatialParameters();
  55349. if (this.isPlaying) {
  55350. if (this._streaming) {
  55351. this._htmlAudioElement.playbackRate = this._playbackRate;
  55352. }
  55353. else {
  55354. if (this._soundSource) {
  55355. this._soundSource.playbackRate.value = this._playbackRate;
  55356. }
  55357. }
  55358. }
  55359. }
  55360. };
  55361. Sound.prototype._createSpatialParameters = function () {
  55362. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55363. if (this._scene.headphone) {
  55364. this._panningModel = "HRTF";
  55365. }
  55366. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  55367. this._updateSpatialParameters();
  55368. this._soundPanner.connect(this._ouputAudioNode);
  55369. this._inputAudioNode = this._soundPanner;
  55370. }
  55371. };
  55372. Sound.prototype._updateSpatialParameters = function () {
  55373. if (this.spatialSound && this._soundPanner) {
  55374. if (this.useCustomAttenuation) {
  55375. // Tricks to disable in a way embedded Web Audio attenuation
  55376. this._soundPanner.distanceModel = "linear";
  55377. this._soundPanner.maxDistance = Number.MAX_VALUE;
  55378. this._soundPanner.refDistance = 1;
  55379. this._soundPanner.rolloffFactor = 1;
  55380. this._soundPanner.panningModel = this._panningModel;
  55381. }
  55382. else {
  55383. this._soundPanner.distanceModel = this.distanceModel;
  55384. this._soundPanner.maxDistance = this.maxDistance;
  55385. this._soundPanner.refDistance = this.refDistance;
  55386. this._soundPanner.rolloffFactor = this.rolloffFactor;
  55387. this._soundPanner.panningModel = this._panningModel;
  55388. }
  55389. }
  55390. };
  55391. Sound.prototype.switchPanningModelToHRTF = function () {
  55392. this._panningModel = "HRTF";
  55393. this._switchPanningModel();
  55394. };
  55395. Sound.prototype.switchPanningModelToEqualPower = function () {
  55396. this._panningModel = "equalpower";
  55397. this._switchPanningModel();
  55398. };
  55399. Sound.prototype._switchPanningModel = function () {
  55400. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55401. this._soundPanner.panningModel = this._panningModel;
  55402. }
  55403. };
  55404. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  55405. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55406. if (this._isOutputConnected) {
  55407. this._ouputAudioNode.disconnect();
  55408. }
  55409. this._ouputAudioNode.connect(soundTrackAudioNode);
  55410. this._isOutputConnected = true;
  55411. }
  55412. };
  55413. /**
  55414. * Transform this sound into a directional source
  55415. * @param coneInnerAngle Size of the inner cone in degree
  55416. * @param coneOuterAngle Size of the outer cone in degree
  55417. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  55418. */
  55419. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  55420. if (coneOuterAngle < coneInnerAngle) {
  55421. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  55422. return;
  55423. }
  55424. this._coneInnerAngle = coneInnerAngle;
  55425. this._coneOuterAngle = coneOuterAngle;
  55426. this._coneOuterGain = coneOuterGain;
  55427. this._isDirectional = true;
  55428. if (this.isPlaying && this.loop) {
  55429. this.stop();
  55430. this.play();
  55431. }
  55432. };
  55433. Sound.prototype.setPosition = function (newPosition) {
  55434. this._position = newPosition;
  55435. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55436. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55437. }
  55438. };
  55439. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  55440. this._localDirection = newLocalDirection;
  55441. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  55442. this._updateDirection();
  55443. }
  55444. };
  55445. Sound.prototype._updateDirection = function () {
  55446. if (!this._connectedMesh || !this._soundPanner) {
  55447. return;
  55448. }
  55449. var mat = this._connectedMesh.getWorldMatrix();
  55450. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  55451. direction.normalize();
  55452. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  55453. };
  55454. Sound.prototype.updateDistanceFromListener = function () {
  55455. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  55456. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  55457. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  55458. }
  55459. };
  55460. Sound.prototype.setAttenuationFunction = function (callback) {
  55461. this._customAttenuationFunction = callback;
  55462. };
  55463. /**
  55464. * Play the sound
  55465. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  55466. * @param offset (optional) Start the sound setting it at a specific time
  55467. */
  55468. Sound.prototype.play = function (time, offset) {
  55469. var _this = this;
  55470. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  55471. try {
  55472. if (this._startOffset < 0) {
  55473. time = -this._startOffset;
  55474. this._startOffset = 0;
  55475. }
  55476. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55477. if (!this._soundSource || !this._streamingSource) {
  55478. if (this.spatialSound && this._soundPanner) {
  55479. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55480. if (this._isDirectional) {
  55481. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  55482. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  55483. this._soundPanner.coneOuterGain = this._coneOuterGain;
  55484. if (this._connectedMesh) {
  55485. this._updateDirection();
  55486. }
  55487. else {
  55488. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  55489. }
  55490. }
  55491. }
  55492. }
  55493. if (this._streaming) {
  55494. if (!this._streamingSource) {
  55495. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  55496. this._htmlAudioElement.onended = function () { _this._onended(); };
  55497. this._htmlAudioElement.playbackRate = this._playbackRate;
  55498. }
  55499. this._streamingSource.disconnect();
  55500. this._streamingSource.connect(this._inputAudioNode);
  55501. this._htmlAudioElement.play();
  55502. }
  55503. else {
  55504. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  55505. this._soundSource.buffer = this._audioBuffer;
  55506. this._soundSource.connect(this._inputAudioNode);
  55507. this._soundSource.loop = this.loop;
  55508. this._soundSource.playbackRate.value = this._playbackRate;
  55509. this._soundSource.onended = function () { _this._onended(); };
  55510. if (this._soundSource.buffer) {
  55511. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  55512. }
  55513. }
  55514. this._startTime = startTime;
  55515. this.isPlaying = true;
  55516. this.isPaused = false;
  55517. }
  55518. catch (ex) {
  55519. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  55520. }
  55521. }
  55522. };
  55523. Sound.prototype._onended = function () {
  55524. this.isPlaying = false;
  55525. if (this.onended) {
  55526. this.onended();
  55527. }
  55528. };
  55529. /**
  55530. * Stop the sound
  55531. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  55532. */
  55533. Sound.prototype.stop = function (time) {
  55534. if (this.isPlaying) {
  55535. if (this._streaming) {
  55536. this._htmlAudioElement.pause();
  55537. // Test needed for Firefox or it will generate an Invalid State Error
  55538. if (this._htmlAudioElement.currentTime > 0) {
  55539. this._htmlAudioElement.currentTime = 0;
  55540. }
  55541. }
  55542. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  55543. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55544. this._soundSource.stop(stopTime);
  55545. this._soundSource.onended = function () { };
  55546. if (!this.isPaused) {
  55547. this._startOffset = 0;
  55548. }
  55549. }
  55550. this.isPlaying = false;
  55551. }
  55552. };
  55553. Sound.prototype.pause = function () {
  55554. if (this.isPlaying) {
  55555. this.isPaused = true;
  55556. if (this._streaming) {
  55557. this._htmlAudioElement.pause();
  55558. }
  55559. else if (BABYLON.Engine.audioEngine.audioContext) {
  55560. this.stop(0);
  55561. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  55562. }
  55563. }
  55564. };
  55565. Sound.prototype.setVolume = function (newVolume, time) {
  55566. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  55567. if (time && BABYLON.Engine.audioEngine.audioContext) {
  55568. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  55569. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  55570. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  55571. }
  55572. else {
  55573. this._soundGain.gain.value = newVolume;
  55574. }
  55575. }
  55576. this._volume = newVolume;
  55577. };
  55578. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  55579. this._playbackRate = newPlaybackRate;
  55580. if (this.isPlaying) {
  55581. if (this._streaming) {
  55582. this._htmlAudioElement.playbackRate = this._playbackRate;
  55583. }
  55584. else if (this._soundSource) {
  55585. this._soundSource.playbackRate.value = this._playbackRate;
  55586. }
  55587. }
  55588. };
  55589. Sound.prototype.getVolume = function () {
  55590. return this._volume;
  55591. };
  55592. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  55593. var _this = this;
  55594. if (this._connectedMesh && this._registerFunc) {
  55595. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55596. this._registerFunc = null;
  55597. }
  55598. this._connectedMesh = meshToConnectTo;
  55599. if (!this.spatialSound) {
  55600. this.spatialSound = true;
  55601. this._createSpatialParameters();
  55602. if (this.isPlaying && this.loop) {
  55603. this.stop();
  55604. this.play();
  55605. }
  55606. }
  55607. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  55608. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  55609. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  55610. };
  55611. Sound.prototype.detachFromMesh = function () {
  55612. if (this._connectedMesh && this._registerFunc) {
  55613. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55614. this._registerFunc = null;
  55615. this._connectedMesh = null;
  55616. }
  55617. };
  55618. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  55619. if (!node.getBoundingInfo) {
  55620. return;
  55621. }
  55622. var mesh = node;
  55623. var boundingInfo = mesh.getBoundingInfo();
  55624. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  55625. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  55626. this._updateDirection();
  55627. }
  55628. };
  55629. Sound.prototype.clone = function () {
  55630. var _this = this;
  55631. if (!this._streaming) {
  55632. var setBufferAndRun = function () {
  55633. if (_this._isReadyToPlay) {
  55634. clonedSound._audioBuffer = _this.getAudioBuffer();
  55635. clonedSound._isReadyToPlay = true;
  55636. if (clonedSound.autoplay) {
  55637. clonedSound.play();
  55638. }
  55639. }
  55640. else {
  55641. window.setTimeout(setBufferAndRun, 300);
  55642. }
  55643. };
  55644. var currentOptions = {
  55645. autoplay: this.autoplay, loop: this.loop,
  55646. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  55647. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  55648. refDistance: this.refDistance, distanceModel: this.distanceModel
  55649. };
  55650. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  55651. if (this.useCustomAttenuation) {
  55652. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  55653. }
  55654. clonedSound.setPosition(this._position);
  55655. clonedSound.setPlaybackRate(this._playbackRate);
  55656. setBufferAndRun();
  55657. return clonedSound;
  55658. }
  55659. else {
  55660. return null;
  55661. }
  55662. };
  55663. Sound.prototype.getAudioBuffer = function () {
  55664. return this._audioBuffer;
  55665. };
  55666. Sound.prototype.serialize = function () {
  55667. var serializationObject = {
  55668. name: this.name,
  55669. url: this.name,
  55670. autoplay: this.autoplay,
  55671. loop: this.loop,
  55672. volume: this._volume,
  55673. spatialSound: this.spatialSound,
  55674. maxDistance: this.maxDistance,
  55675. rolloffFactor: this.rolloffFactor,
  55676. refDistance: this.refDistance,
  55677. distanceModel: this.distanceModel,
  55678. playbackRate: this._playbackRate,
  55679. panningModel: this._panningModel,
  55680. soundTrackId: this.soundTrackId
  55681. };
  55682. if (this.spatialSound) {
  55683. if (this._connectedMesh)
  55684. serializationObject.connectedMeshId = this._connectedMesh.id;
  55685. serializationObject.position = this._position.asArray();
  55686. serializationObject.refDistance = this.refDistance;
  55687. serializationObject.distanceModel = this.distanceModel;
  55688. serializationObject.isDirectional = this._isDirectional;
  55689. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  55690. serializationObject.coneInnerAngle = this._coneInnerAngle;
  55691. serializationObject.coneOuterAngle = this._coneOuterAngle;
  55692. serializationObject.coneOuterGain = this._coneOuterGain;
  55693. }
  55694. return serializationObject;
  55695. };
  55696. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  55697. var soundName = parsedSound.name;
  55698. var soundUrl;
  55699. if (parsedSound.url) {
  55700. soundUrl = rootUrl + parsedSound.url;
  55701. }
  55702. else {
  55703. soundUrl = rootUrl + soundName;
  55704. }
  55705. var options = {
  55706. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  55707. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  55708. rolloffFactor: parsedSound.rolloffFactor,
  55709. refDistance: parsedSound.refDistance,
  55710. distanceModel: parsedSound.distanceModel,
  55711. playbackRate: parsedSound.playbackRate
  55712. };
  55713. var newSound;
  55714. if (!sourceSound) {
  55715. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  55716. scene._addPendingData(newSound);
  55717. }
  55718. else {
  55719. var setBufferAndRun = function () {
  55720. if (sourceSound._isReadyToPlay) {
  55721. newSound._audioBuffer = sourceSound.getAudioBuffer();
  55722. newSound._isReadyToPlay = true;
  55723. if (newSound.autoplay) {
  55724. newSound.play();
  55725. }
  55726. }
  55727. else {
  55728. window.setTimeout(setBufferAndRun, 300);
  55729. }
  55730. };
  55731. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  55732. setBufferAndRun();
  55733. }
  55734. if (parsedSound.position) {
  55735. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  55736. newSound.setPosition(soundPosition);
  55737. }
  55738. if (parsedSound.isDirectional) {
  55739. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  55740. if (parsedSound.localDirectionToMesh) {
  55741. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  55742. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  55743. }
  55744. }
  55745. if (parsedSound.connectedMeshId) {
  55746. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  55747. if (connectedMesh) {
  55748. newSound.attachToMesh(connectedMesh);
  55749. }
  55750. }
  55751. return newSound;
  55752. };
  55753. return Sound;
  55754. }());
  55755. BABYLON.Sound = Sound;
  55756. })(BABYLON || (BABYLON = {}));
  55757. //# sourceMappingURL=babylon.sound.js.map
  55758. var BABYLON;
  55759. (function (BABYLON) {
  55760. var SoundTrack = /** @class */ (function () {
  55761. function SoundTrack(scene, options) {
  55762. this.id = -1;
  55763. this._isMainTrack = false;
  55764. this._isInitialized = false;
  55765. this._scene = scene;
  55766. this.soundCollection = new Array();
  55767. this._options = options;
  55768. if (!this._isMainTrack) {
  55769. this._scene.soundTracks.push(this);
  55770. this.id = this._scene.soundTracks.length - 1;
  55771. }
  55772. }
  55773. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  55774. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55775. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  55776. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  55777. if (this._options) {
  55778. if (this._options.volume) {
  55779. this._outputAudioNode.gain.value = this._options.volume;
  55780. }
  55781. if (this._options.mainTrack) {
  55782. this._isMainTrack = this._options.mainTrack;
  55783. }
  55784. }
  55785. this._isInitialized = true;
  55786. }
  55787. };
  55788. SoundTrack.prototype.dispose = function () {
  55789. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55790. if (this._connectedAnalyser) {
  55791. this._connectedAnalyser.stopDebugCanvas();
  55792. }
  55793. while (this.soundCollection.length) {
  55794. this.soundCollection[0].dispose();
  55795. }
  55796. if (this._outputAudioNode) {
  55797. this._outputAudioNode.disconnect();
  55798. }
  55799. this._outputAudioNode = null;
  55800. }
  55801. };
  55802. SoundTrack.prototype.AddSound = function (sound) {
  55803. if (!this._isInitialized) {
  55804. this._initializeSoundTrackAudioGraph();
  55805. }
  55806. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55807. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  55808. }
  55809. if (sound.soundTrackId) {
  55810. if (sound.soundTrackId === -1) {
  55811. this._scene.mainSoundTrack.RemoveSound(sound);
  55812. }
  55813. else {
  55814. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  55815. }
  55816. }
  55817. this.soundCollection.push(sound);
  55818. sound.soundTrackId = this.id;
  55819. };
  55820. SoundTrack.prototype.RemoveSound = function (sound) {
  55821. var index = this.soundCollection.indexOf(sound);
  55822. if (index !== -1) {
  55823. this.soundCollection.splice(index, 1);
  55824. }
  55825. };
  55826. SoundTrack.prototype.setVolume = function (newVolume) {
  55827. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55828. this._outputAudioNode.gain.value = newVolume;
  55829. }
  55830. };
  55831. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  55832. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55833. for (var i = 0; i < this.soundCollection.length; i++) {
  55834. this.soundCollection[i].switchPanningModelToHRTF();
  55835. }
  55836. }
  55837. };
  55838. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  55839. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55840. for (var i = 0; i < this.soundCollection.length; i++) {
  55841. this.soundCollection[i].switchPanningModelToEqualPower();
  55842. }
  55843. }
  55844. };
  55845. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  55846. if (this._connectedAnalyser) {
  55847. this._connectedAnalyser.stopDebugCanvas();
  55848. }
  55849. this._connectedAnalyser = analyser;
  55850. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55851. this._outputAudioNode.disconnect();
  55852. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  55853. }
  55854. };
  55855. return SoundTrack;
  55856. }());
  55857. BABYLON.SoundTrack = SoundTrack;
  55858. })(BABYLON || (BABYLON = {}));
  55859. //# sourceMappingURL=babylon.soundtrack.js.map
  55860. var BABYLON;
  55861. (function (BABYLON) {
  55862. var Analyser = /** @class */ (function () {
  55863. function Analyser(scene) {
  55864. this.SMOOTHING = 0.75;
  55865. this.FFT_SIZE = 512;
  55866. this.BARGRAPHAMPLITUDE = 256;
  55867. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  55868. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  55869. this._scene = scene;
  55870. this._audioEngine = BABYLON.Engine.audioEngine;
  55871. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  55872. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  55873. this._webAudioAnalyser.minDecibels = -140;
  55874. this._webAudioAnalyser.maxDecibels = 0;
  55875. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55876. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55877. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  55878. }
  55879. }
  55880. Analyser.prototype.getFrequencyBinCount = function () {
  55881. if (this._audioEngine.canUseWebAudio) {
  55882. return this._webAudioAnalyser.frequencyBinCount;
  55883. }
  55884. else {
  55885. return 0;
  55886. }
  55887. };
  55888. Analyser.prototype.getByteFrequencyData = function () {
  55889. if (this._audioEngine.canUseWebAudio) {
  55890. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55891. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55892. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  55893. }
  55894. return this._byteFreqs;
  55895. };
  55896. Analyser.prototype.getByteTimeDomainData = function () {
  55897. if (this._audioEngine.canUseWebAudio) {
  55898. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55899. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55900. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  55901. }
  55902. return this._byteTime;
  55903. };
  55904. Analyser.prototype.getFloatFrequencyData = function () {
  55905. if (this._audioEngine.canUseWebAudio) {
  55906. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55907. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55908. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  55909. }
  55910. return this._floatFreqs;
  55911. };
  55912. Analyser.prototype.drawDebugCanvas = function () {
  55913. var _this = this;
  55914. if (this._audioEngine.canUseWebAudio) {
  55915. if (!this._debugCanvas) {
  55916. this._debugCanvas = document.createElement("canvas");
  55917. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  55918. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  55919. this._debugCanvas.style.position = "absolute";
  55920. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  55921. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  55922. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  55923. document.body.appendChild(this._debugCanvas);
  55924. this._registerFunc = function () {
  55925. _this.drawDebugCanvas();
  55926. };
  55927. this._scene.registerBeforeRender(this._registerFunc);
  55928. }
  55929. if (this._registerFunc && this._debugCanvasContext) {
  55930. var workingArray = this.getByteFrequencyData();
  55931. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  55932. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  55933. // Draw the frequency domain chart.
  55934. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  55935. var value = workingArray[i];
  55936. var percent = value / this.BARGRAPHAMPLITUDE;
  55937. var height = this.DEBUGCANVASSIZE.height * percent;
  55938. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  55939. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  55940. var hue = i / this.getFrequencyBinCount() * 360;
  55941. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  55942. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  55943. }
  55944. }
  55945. }
  55946. };
  55947. Analyser.prototype.stopDebugCanvas = function () {
  55948. if (this._debugCanvas) {
  55949. if (this._registerFunc) {
  55950. this._scene.unregisterBeforeRender(this._registerFunc);
  55951. this._registerFunc = null;
  55952. }
  55953. document.body.removeChild(this._debugCanvas);
  55954. this._debugCanvas = null;
  55955. this._debugCanvasContext = null;
  55956. }
  55957. };
  55958. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  55959. if (this._audioEngine.canUseWebAudio) {
  55960. inputAudioNode.connect(this._webAudioAnalyser);
  55961. this._webAudioAnalyser.connect(outputAudioNode);
  55962. }
  55963. };
  55964. Analyser.prototype.dispose = function () {
  55965. if (this._audioEngine.canUseWebAudio) {
  55966. this._webAudioAnalyser.disconnect();
  55967. }
  55968. };
  55969. return Analyser;
  55970. }());
  55971. BABYLON.Analyser = Analyser;
  55972. })(BABYLON || (BABYLON = {}));
  55973. //# sourceMappingURL=babylon.analyser.js.map
  55974. var BABYLON;
  55975. (function (BABYLON) {
  55976. var CubeTexture = /** @class */ (function (_super) {
  55977. __extends(CubeTexture, _super);
  55978. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  55979. if (extensions === void 0) { extensions = null; }
  55980. if (noMipmap === void 0) { noMipmap = false; }
  55981. if (files === void 0) { files = null; }
  55982. if (onLoad === void 0) { onLoad = null; }
  55983. if (onError === void 0) { onError = null; }
  55984. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  55985. if (prefiltered === void 0) { prefiltered = false; }
  55986. if (forcedExtension === void 0) { forcedExtension = null; }
  55987. var _this = _super.call(this, scene) || this;
  55988. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  55989. /**
  55990. * Gets or sets the center of the bounding box associated with the cube texture
  55991. * It must define where the camera used to render the texture was set
  55992. */
  55993. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  55994. _this.name = rootUrl;
  55995. _this.url = rootUrl;
  55996. _this._noMipmap = noMipmap;
  55997. _this.hasAlpha = false;
  55998. _this._format = format;
  55999. _this._prefiltered = prefiltered;
  56000. _this.isCube = true;
  56001. _this._textureMatrix = BABYLON.Matrix.Identity();
  56002. if (prefiltered) {
  56003. _this.gammaSpace = false;
  56004. }
  56005. if (!rootUrl && !files) {
  56006. return _this;
  56007. }
  56008. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  56009. var lastDot = rootUrl.lastIndexOf(".");
  56010. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  56011. var isDDS = (extension === ".dds");
  56012. if (!files) {
  56013. if (!isDDS && !extensions) {
  56014. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  56015. }
  56016. files = [];
  56017. if (extensions) {
  56018. for (var index = 0; index < extensions.length; index++) {
  56019. files.push(rootUrl + extensions[index]);
  56020. }
  56021. }
  56022. }
  56023. _this._files = files;
  56024. if (!_this._texture) {
  56025. if (!scene.useDelayedTextureLoading) {
  56026. if (prefiltered) {
  56027. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  56028. }
  56029. else {
  56030. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  56031. }
  56032. }
  56033. else {
  56034. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56035. }
  56036. }
  56037. else if (onLoad) {
  56038. if (_this._texture.isReady) {
  56039. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  56040. }
  56041. else {
  56042. _this._texture.onLoadedObservable.add(onLoad);
  56043. }
  56044. }
  56045. return _this;
  56046. }
  56047. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  56048. get: function () {
  56049. return this._boundingBoxSize;
  56050. },
  56051. /**
  56052. * Gets or sets the size of the bounding box associated with the cube texture
  56053. * When defined, the cubemap will switch to local mode
  56054. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56055. * @example https://www.babylonjs-playground.com/#RNASML
  56056. */
  56057. set: function (value) {
  56058. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56059. return;
  56060. }
  56061. this._boundingBoxSize = value;
  56062. var scene = this.getScene();
  56063. if (scene) {
  56064. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56065. }
  56066. },
  56067. enumerable: true,
  56068. configurable: true
  56069. });
  56070. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  56071. return new CubeTexture("", scene, null, noMipmap, files);
  56072. };
  56073. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  56074. if (forcedExtension === void 0) { forcedExtension = null; }
  56075. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  56076. };
  56077. // Methods
  56078. CubeTexture.prototype.delayLoad = function () {
  56079. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56080. return;
  56081. }
  56082. var scene = this.getScene();
  56083. if (!scene) {
  56084. return;
  56085. }
  56086. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56087. this._texture = this._getFromCache(this.url, this._noMipmap);
  56088. if (!this._texture) {
  56089. if (this._prefiltered) {
  56090. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  56091. }
  56092. else {
  56093. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  56094. }
  56095. }
  56096. };
  56097. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  56098. return this._textureMatrix;
  56099. };
  56100. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  56101. this._textureMatrix = value;
  56102. };
  56103. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56104. var texture = BABYLON.SerializationHelper.Parse(function () {
  56105. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  56106. }, parsedTexture, scene);
  56107. // Animations
  56108. if (parsedTexture.animations) {
  56109. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  56110. var parsedAnimation = parsedTexture.animations[animationIndex];
  56111. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56112. }
  56113. }
  56114. return texture;
  56115. };
  56116. CubeTexture.prototype.clone = function () {
  56117. var _this = this;
  56118. return BABYLON.SerializationHelper.Clone(function () {
  56119. var scene = _this.getScene();
  56120. if (!scene) {
  56121. return _this;
  56122. }
  56123. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  56124. }, this);
  56125. };
  56126. return CubeTexture;
  56127. }(BABYLON.BaseTexture));
  56128. BABYLON.CubeTexture = CubeTexture;
  56129. })(BABYLON || (BABYLON = {}));
  56130. //# sourceMappingURL=babylon.cubeTexture.js.map
  56131. var BABYLON;
  56132. (function (BABYLON) {
  56133. var RenderTargetTexture = /** @class */ (function (_super) {
  56134. __extends(RenderTargetTexture, _super);
  56135. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  56136. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  56137. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56138. if (isCube === void 0) { isCube = false; }
  56139. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56140. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56141. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  56142. if (isMulti === void 0) { isMulti = false; }
  56143. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56144. _this.isCube = isCube;
  56145. /**
  56146. * Use this list to define the list of mesh you want to render.
  56147. */
  56148. _this.renderList = new Array();
  56149. _this.renderParticles = true;
  56150. _this.renderSprites = false;
  56151. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  56152. _this.ignoreCameraViewport = false;
  56153. // Events
  56154. /**
  56155. * An event triggered when the texture is unbind.
  56156. * @type {BABYLON.Observable}
  56157. */
  56158. _this.onBeforeBindObservable = new BABYLON.Observable();
  56159. /**
  56160. * An event triggered when the texture is unbind.
  56161. * @type {BABYLON.Observable}
  56162. */
  56163. _this.onAfterUnbindObservable = new BABYLON.Observable();
  56164. /**
  56165. * An event triggered before rendering the texture
  56166. * @type {BABYLON.Observable}
  56167. */
  56168. _this.onBeforeRenderObservable = new BABYLON.Observable();
  56169. /**
  56170. * An event triggered after rendering the texture
  56171. * @type {BABYLON.Observable}
  56172. */
  56173. _this.onAfterRenderObservable = new BABYLON.Observable();
  56174. /**
  56175. * An event triggered after the texture clear
  56176. * @type {BABYLON.Observable}
  56177. */
  56178. _this.onClearObservable = new BABYLON.Observable();
  56179. _this._currentRefreshId = -1;
  56180. _this._refreshRate = 1;
  56181. _this._samples = 1;
  56182. /**
  56183. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  56184. * It must define where the camera used to render the texture is set
  56185. */
  56186. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56187. scene = _this.getScene();
  56188. if (!scene) {
  56189. return _this;
  56190. }
  56191. _this._engine = scene.getEngine();
  56192. _this.name = name;
  56193. _this.isRenderTarget = true;
  56194. _this._initialSizeParameter = size;
  56195. _this._processSizeParameter(size);
  56196. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  56197. });
  56198. _this._generateMipMaps = generateMipMaps ? true : false;
  56199. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  56200. // Rendering groups
  56201. _this._renderingManager = new BABYLON.RenderingManager(scene);
  56202. if (isMulti) {
  56203. return _this;
  56204. }
  56205. _this._renderTargetOptions = {
  56206. generateMipMaps: generateMipMaps,
  56207. type: type,
  56208. samplingMode: samplingMode,
  56209. generateDepthBuffer: generateDepthBuffer,
  56210. generateStencilBuffer: generateStencilBuffer
  56211. };
  56212. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  56213. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56214. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56215. }
  56216. if (isCube) {
  56217. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  56218. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  56219. _this._textureMatrix = BABYLON.Matrix.Identity();
  56220. }
  56221. else {
  56222. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  56223. }
  56224. return _this;
  56225. }
  56226. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  56227. get: function () {
  56228. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  56229. },
  56230. enumerable: true,
  56231. configurable: true
  56232. });
  56233. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  56234. get: function () {
  56235. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  56236. },
  56237. enumerable: true,
  56238. configurable: true
  56239. });
  56240. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  56241. get: function () {
  56242. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  56243. },
  56244. enumerable: true,
  56245. configurable: true
  56246. });
  56247. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  56248. set: function (callback) {
  56249. if (this._onAfterUnbindObserver) {
  56250. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  56251. }
  56252. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  56253. },
  56254. enumerable: true,
  56255. configurable: true
  56256. });
  56257. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  56258. set: function (callback) {
  56259. if (this._onBeforeRenderObserver) {
  56260. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  56261. }
  56262. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  56263. },
  56264. enumerable: true,
  56265. configurable: true
  56266. });
  56267. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  56268. set: function (callback) {
  56269. if (this._onAfterRenderObserver) {
  56270. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  56271. }
  56272. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  56273. },
  56274. enumerable: true,
  56275. configurable: true
  56276. });
  56277. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  56278. set: function (callback) {
  56279. if (this._onClearObserver) {
  56280. this.onClearObservable.remove(this._onClearObserver);
  56281. }
  56282. this._onClearObserver = this.onClearObservable.add(callback);
  56283. },
  56284. enumerable: true,
  56285. configurable: true
  56286. });
  56287. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  56288. get: function () {
  56289. return this._renderTargetOptions;
  56290. },
  56291. enumerable: true,
  56292. configurable: true
  56293. });
  56294. RenderTargetTexture.prototype._onRatioRescale = function () {
  56295. if (this._sizeRatio) {
  56296. this.resize(this._initialSizeParameter);
  56297. }
  56298. };
  56299. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  56300. get: function () {
  56301. return this._boundingBoxSize;
  56302. },
  56303. /**
  56304. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  56305. * When defined, the cubemap will switch to local mode
  56306. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56307. * @example https://www.babylonjs-playground.com/#RNASML
  56308. */
  56309. set: function (value) {
  56310. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56311. return;
  56312. }
  56313. this._boundingBoxSize = value;
  56314. var scene = this.getScene();
  56315. if (scene) {
  56316. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56317. }
  56318. },
  56319. enumerable: true,
  56320. configurable: true
  56321. });
  56322. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  56323. if (size.ratio) {
  56324. this._sizeRatio = size.ratio;
  56325. this._size = {
  56326. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  56327. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  56328. };
  56329. }
  56330. else {
  56331. this._size = size;
  56332. }
  56333. };
  56334. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  56335. get: function () {
  56336. return this._samples;
  56337. },
  56338. set: function (value) {
  56339. if (this._samples === value) {
  56340. return;
  56341. }
  56342. var scene = this.getScene();
  56343. if (!scene) {
  56344. return;
  56345. }
  56346. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  56347. },
  56348. enumerable: true,
  56349. configurable: true
  56350. });
  56351. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  56352. this._currentRefreshId = -1;
  56353. };
  56354. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  56355. get: function () {
  56356. return this._refreshRate;
  56357. },
  56358. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56359. set: function (value) {
  56360. this._refreshRate = value;
  56361. this.resetRefreshCounter();
  56362. },
  56363. enumerable: true,
  56364. configurable: true
  56365. });
  56366. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  56367. if (!this._postProcessManager) {
  56368. var scene = this.getScene();
  56369. if (!scene) {
  56370. return;
  56371. }
  56372. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  56373. this._postProcesses = new Array();
  56374. }
  56375. this._postProcesses.push(postProcess);
  56376. this._postProcesses[0].autoClear = false;
  56377. };
  56378. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  56379. if (!this._postProcesses) {
  56380. return;
  56381. }
  56382. if (dispose) {
  56383. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  56384. var postProcess = _a[_i];
  56385. postProcess.dispose();
  56386. }
  56387. }
  56388. this._postProcesses = [];
  56389. };
  56390. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  56391. if (!this._postProcesses) {
  56392. return;
  56393. }
  56394. var index = this._postProcesses.indexOf(postProcess);
  56395. if (index === -1) {
  56396. return;
  56397. }
  56398. this._postProcesses.splice(index, 1);
  56399. if (this._postProcesses.length > 0) {
  56400. this._postProcesses[0].autoClear = false;
  56401. }
  56402. };
  56403. RenderTargetTexture.prototype._shouldRender = function () {
  56404. if (this._currentRefreshId === -1) {
  56405. this._currentRefreshId = 1;
  56406. return true;
  56407. }
  56408. if (this.refreshRate === this._currentRefreshId) {
  56409. this._currentRefreshId = 1;
  56410. return true;
  56411. }
  56412. this._currentRefreshId++;
  56413. return false;
  56414. };
  56415. RenderTargetTexture.prototype.getRenderSize = function () {
  56416. if (this._size.width) {
  56417. return this._size.width;
  56418. }
  56419. return this._size;
  56420. };
  56421. RenderTargetTexture.prototype.getRenderWidth = function () {
  56422. if (this._size.width) {
  56423. return this._size.width;
  56424. }
  56425. return this._size;
  56426. };
  56427. RenderTargetTexture.prototype.getRenderHeight = function () {
  56428. if (this._size.width) {
  56429. return this._size.height;
  56430. }
  56431. return this._size;
  56432. };
  56433. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  56434. get: function () {
  56435. return true;
  56436. },
  56437. enumerable: true,
  56438. configurable: true
  56439. });
  56440. RenderTargetTexture.prototype.scale = function (ratio) {
  56441. var newSize = this.getRenderSize() * ratio;
  56442. this.resize(newSize);
  56443. };
  56444. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  56445. if (this.isCube) {
  56446. return this._textureMatrix;
  56447. }
  56448. return _super.prototype.getReflectionTextureMatrix.call(this);
  56449. };
  56450. RenderTargetTexture.prototype.resize = function (size) {
  56451. this.releaseInternalTexture();
  56452. var scene = this.getScene();
  56453. if (!scene) {
  56454. return;
  56455. }
  56456. this._processSizeParameter(size);
  56457. if (this.isCube) {
  56458. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  56459. }
  56460. else {
  56461. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  56462. }
  56463. };
  56464. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  56465. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  56466. if (dumpForDebug === void 0) { dumpForDebug = false; }
  56467. var scene = this.getScene();
  56468. if (!scene) {
  56469. return;
  56470. }
  56471. var engine = scene.getEngine();
  56472. if (this.useCameraPostProcesses !== undefined) {
  56473. useCameraPostProcess = this.useCameraPostProcesses;
  56474. }
  56475. if (this._waitingRenderList) {
  56476. this.renderList = [];
  56477. for (var index = 0; index < this._waitingRenderList.length; index++) {
  56478. var id = this._waitingRenderList[index];
  56479. var mesh_1 = scene.getMeshByID(id);
  56480. if (mesh_1) {
  56481. this.renderList.push(mesh_1);
  56482. }
  56483. }
  56484. delete this._waitingRenderList;
  56485. }
  56486. // Is predicate defined?
  56487. if (this.renderListPredicate) {
  56488. if (this.renderList) {
  56489. this.renderList.splice(0); // Clear previous renderList
  56490. }
  56491. else {
  56492. this.renderList = [];
  56493. }
  56494. var scene = this.getScene();
  56495. if (!scene) {
  56496. return;
  56497. }
  56498. var sceneMeshes = scene.meshes;
  56499. for (var index = 0; index < sceneMeshes.length; index++) {
  56500. var mesh = sceneMeshes[index];
  56501. if (this.renderListPredicate(mesh)) {
  56502. this.renderList.push(mesh);
  56503. }
  56504. }
  56505. }
  56506. this.onBeforeBindObservable.notifyObservers(this);
  56507. // Set custom projection.
  56508. // Needs to be before binding to prevent changing the aspect ratio.
  56509. var camera;
  56510. if (this.activeCamera) {
  56511. camera = this.activeCamera;
  56512. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56513. if (this.activeCamera !== scene.activeCamera) {
  56514. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  56515. }
  56516. }
  56517. else {
  56518. camera = scene.activeCamera;
  56519. if (camera) {
  56520. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56521. }
  56522. }
  56523. // Prepare renderingManager
  56524. this._renderingManager.reset();
  56525. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  56526. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  56527. var sceneRenderId = scene.getRenderId();
  56528. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  56529. var mesh = currentRenderList[meshIndex];
  56530. if (mesh) {
  56531. if (!mesh.isReady()) {
  56532. // Reset _currentRefreshId
  56533. this.resetRefreshCounter();
  56534. continue;
  56535. }
  56536. mesh._preActivateForIntermediateRendering(sceneRenderId);
  56537. var isMasked = void 0;
  56538. if (!this.renderList && camera) {
  56539. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  56540. }
  56541. else {
  56542. isMasked = false;
  56543. }
  56544. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  56545. mesh._activate(sceneRenderId);
  56546. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  56547. var subMesh = mesh.subMeshes[subIndex];
  56548. scene._activeIndices.addCount(subMesh.indexCount, false);
  56549. this._renderingManager.dispatch(subMesh, mesh);
  56550. }
  56551. }
  56552. }
  56553. }
  56554. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  56555. var particleSystem = scene.particleSystems[particleIndex];
  56556. var emitter = particleSystem.emitter;
  56557. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  56558. continue;
  56559. }
  56560. if (currentRenderList.indexOf(emitter) >= 0) {
  56561. this._renderingManager.dispatchParticles(particleSystem);
  56562. }
  56563. }
  56564. if (this.isCube) {
  56565. for (var face = 0; face < 6; face++) {
  56566. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56567. scene.incrementRenderId();
  56568. scene.resetCachedMaterial();
  56569. }
  56570. }
  56571. else {
  56572. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56573. }
  56574. this.onAfterUnbindObservable.notifyObservers(this);
  56575. if (scene.activeCamera) {
  56576. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  56577. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  56578. }
  56579. engine.setViewport(scene.activeCamera.viewport);
  56580. }
  56581. scene.resetCachedMaterial();
  56582. };
  56583. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  56584. var minimum = 128;
  56585. var x = renderDimension * scale;
  56586. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  56587. // Ensure we don't exceed the render dimension (while staying POT)
  56588. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  56589. };
  56590. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56591. var _this = this;
  56592. if (!this._texture) {
  56593. return;
  56594. }
  56595. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  56596. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56597. });
  56598. };
  56599. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  56600. var scene = this.getScene();
  56601. if (!scene) {
  56602. return;
  56603. }
  56604. var engine = scene.getEngine();
  56605. if (!this._texture) {
  56606. return;
  56607. }
  56608. // Bind
  56609. if (this._postProcessManager) {
  56610. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  56611. }
  56612. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  56613. if (this._texture) {
  56614. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  56615. }
  56616. }
  56617. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  56618. // Clear
  56619. if (this.onClearObservable.hasObservers()) {
  56620. this.onClearObservable.notifyObservers(engine);
  56621. }
  56622. else {
  56623. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  56624. }
  56625. if (!this._doNotChangeAspectRatio) {
  56626. scene.updateTransformMatrix(true);
  56627. }
  56628. // Render
  56629. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  56630. if (this._postProcessManager) {
  56631. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  56632. }
  56633. else if (useCameraPostProcess) {
  56634. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  56635. }
  56636. if (!this._doNotChangeAspectRatio) {
  56637. scene.updateTransformMatrix(true);
  56638. }
  56639. // Dump ?
  56640. if (dumpForDebug) {
  56641. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  56642. }
  56643. // Unbind
  56644. if (!this.isCube || faceIndex === 5) {
  56645. if (this.isCube) {
  56646. if (faceIndex === 5) {
  56647. engine.generateMipMapsForCubemap(this._texture);
  56648. }
  56649. }
  56650. this.unbindFrameBuffer(engine, faceIndex);
  56651. }
  56652. else {
  56653. this.onAfterRenderObservable.notifyObservers(faceIndex);
  56654. }
  56655. };
  56656. /**
  56657. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  56658. * This allowed control for front to back rendering or reversly depending of the special needs.
  56659. *
  56660. * @param renderingGroupId The rendering group id corresponding to its index
  56661. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  56662. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  56663. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  56664. */
  56665. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  56666. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  56667. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  56668. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  56669. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  56670. };
  56671. /**
  56672. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  56673. *
  56674. * @param renderingGroupId The rendering group id corresponding to its index
  56675. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  56676. */
  56677. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  56678. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  56679. };
  56680. RenderTargetTexture.prototype.clone = function () {
  56681. var textureSize = this.getSize();
  56682. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  56683. // Base texture
  56684. newTexture.hasAlpha = this.hasAlpha;
  56685. newTexture.level = this.level;
  56686. // RenderTarget Texture
  56687. newTexture.coordinatesMode = this.coordinatesMode;
  56688. if (this.renderList) {
  56689. newTexture.renderList = this.renderList.slice(0);
  56690. }
  56691. return newTexture;
  56692. };
  56693. RenderTargetTexture.prototype.serialize = function () {
  56694. if (!this.name) {
  56695. return null;
  56696. }
  56697. var serializationObject = _super.prototype.serialize.call(this);
  56698. serializationObject.renderTargetSize = this.getRenderSize();
  56699. serializationObject.renderList = [];
  56700. if (this.renderList) {
  56701. for (var index = 0; index < this.renderList.length; index++) {
  56702. serializationObject.renderList.push(this.renderList[index].id);
  56703. }
  56704. }
  56705. return serializationObject;
  56706. };
  56707. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  56708. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  56709. var objBuffer = this.getInternalTexture();
  56710. var scene = this.getScene();
  56711. if (objBuffer && scene) {
  56712. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  56713. }
  56714. };
  56715. RenderTargetTexture.prototype.dispose = function () {
  56716. if (this._postProcessManager) {
  56717. this._postProcessManager.dispose();
  56718. this._postProcessManager = null;
  56719. }
  56720. this.clearPostProcesses(true);
  56721. if (this._resizeObserver) {
  56722. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  56723. this._resizeObserver = null;
  56724. }
  56725. this.renderList = null;
  56726. // Remove from custom render targets
  56727. var scene = this.getScene();
  56728. if (!scene) {
  56729. return;
  56730. }
  56731. var index = scene.customRenderTargets.indexOf(this);
  56732. if (index >= 0) {
  56733. scene.customRenderTargets.splice(index, 1);
  56734. }
  56735. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  56736. var camera = _a[_i];
  56737. index = camera.customRenderTargets.indexOf(this);
  56738. if (index >= 0) {
  56739. camera.customRenderTargets.splice(index, 1);
  56740. }
  56741. }
  56742. _super.prototype.dispose.call(this);
  56743. };
  56744. RenderTargetTexture.prototype._rebuild = function () {
  56745. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56746. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56747. }
  56748. if (this._postProcessManager) {
  56749. this._postProcessManager._rebuild();
  56750. }
  56751. };
  56752. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  56753. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  56754. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  56755. return RenderTargetTexture;
  56756. }(BABYLON.Texture));
  56757. BABYLON.RenderTargetTexture = RenderTargetTexture;
  56758. })(BABYLON || (BABYLON = {}));
  56759. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  56760. var BABYLON;
  56761. (function (BABYLON) {
  56762. ;
  56763. var MultiRenderTarget = /** @class */ (function (_super) {
  56764. __extends(MultiRenderTarget, _super);
  56765. function MultiRenderTarget(name, size, count, scene, options) {
  56766. var _this = this;
  56767. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  56768. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  56769. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  56770. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  56771. _this._engine = scene.getEngine();
  56772. if (!_this.isSupported) {
  56773. _this.dispose();
  56774. return;
  56775. }
  56776. var types = [];
  56777. var samplingModes = [];
  56778. for (var i = 0; i < count; i++) {
  56779. if (options && options.types && options.types[i] !== undefined) {
  56780. types.push(options.types[i]);
  56781. }
  56782. else {
  56783. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56784. }
  56785. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  56786. samplingModes.push(options.samplingModes[i]);
  56787. }
  56788. else {
  56789. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56790. }
  56791. }
  56792. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  56793. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  56794. _this._size = size;
  56795. _this._multiRenderTargetOptions = {
  56796. samplingModes: samplingModes,
  56797. generateMipMaps: generateMipMaps,
  56798. generateDepthBuffer: generateDepthBuffer,
  56799. generateStencilBuffer: generateStencilBuffer,
  56800. generateDepthTexture: generateDepthTexture,
  56801. types: types,
  56802. textureCount: count
  56803. };
  56804. _this._createInternalTextures();
  56805. _this._createTextures();
  56806. return _this;
  56807. }
  56808. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  56809. get: function () {
  56810. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  56811. },
  56812. enumerable: true,
  56813. configurable: true
  56814. });
  56815. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  56816. get: function () {
  56817. return this._textures;
  56818. },
  56819. enumerable: true,
  56820. configurable: true
  56821. });
  56822. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  56823. get: function () {
  56824. return this._textures[this._textures.length - 1];
  56825. },
  56826. enumerable: true,
  56827. configurable: true
  56828. });
  56829. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  56830. set: function (wrap) {
  56831. if (this._textures) {
  56832. for (var i = 0; i < this._textures.length; i++) {
  56833. this._textures[i].wrapU = wrap;
  56834. }
  56835. }
  56836. },
  56837. enumerable: true,
  56838. configurable: true
  56839. });
  56840. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  56841. set: function (wrap) {
  56842. if (this._textures) {
  56843. for (var i = 0; i < this._textures.length; i++) {
  56844. this._textures[i].wrapV = wrap;
  56845. }
  56846. }
  56847. },
  56848. enumerable: true,
  56849. configurable: true
  56850. });
  56851. MultiRenderTarget.prototype._rebuild = function () {
  56852. this.releaseInternalTextures();
  56853. this._createInternalTextures();
  56854. for (var i = 0; i < this._internalTextures.length; i++) {
  56855. var texture = this._textures[i];
  56856. texture._texture = this._internalTextures[i];
  56857. }
  56858. // Keeps references to frame buffer and stencil/depth buffer
  56859. this._texture = this._internalTextures[0];
  56860. };
  56861. MultiRenderTarget.prototype._createInternalTextures = function () {
  56862. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  56863. };
  56864. MultiRenderTarget.prototype._createTextures = function () {
  56865. this._textures = [];
  56866. for (var i = 0; i < this._internalTextures.length; i++) {
  56867. var texture = new BABYLON.Texture(null, this.getScene());
  56868. texture._texture = this._internalTextures[i];
  56869. this._textures.push(texture);
  56870. }
  56871. // Keeps references to frame buffer and stencil/depth buffer
  56872. this._texture = this._internalTextures[0];
  56873. };
  56874. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  56875. get: function () {
  56876. return this._samples;
  56877. },
  56878. set: function (value) {
  56879. if (this._samples === value) {
  56880. return;
  56881. }
  56882. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  56883. },
  56884. enumerable: true,
  56885. configurable: true
  56886. });
  56887. MultiRenderTarget.prototype.resize = function (size) {
  56888. this.releaseInternalTextures();
  56889. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  56890. this._createInternalTextures();
  56891. };
  56892. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56893. var _this = this;
  56894. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  56895. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56896. });
  56897. };
  56898. MultiRenderTarget.prototype.dispose = function () {
  56899. this.releaseInternalTextures();
  56900. _super.prototype.dispose.call(this);
  56901. };
  56902. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  56903. if (!this._internalTextures) {
  56904. return;
  56905. }
  56906. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  56907. if (this._internalTextures[i] !== undefined) {
  56908. this._internalTextures[i].dispose();
  56909. this._internalTextures.splice(i, 1);
  56910. }
  56911. }
  56912. };
  56913. return MultiRenderTarget;
  56914. }(BABYLON.RenderTargetTexture));
  56915. BABYLON.MultiRenderTarget = MultiRenderTarget;
  56916. })(BABYLON || (BABYLON = {}));
  56917. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  56918. var BABYLON;
  56919. (function (BABYLON) {
  56920. var MirrorTexture = /** @class */ (function (_super) {
  56921. __extends(MirrorTexture, _super);
  56922. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  56923. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56924. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56925. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56926. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  56927. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  56928. _this._transformMatrix = BABYLON.Matrix.Zero();
  56929. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  56930. _this._adaptiveBlurKernel = 0;
  56931. _this._blurKernelX = 0;
  56932. _this._blurKernelY = 0;
  56933. _this._blurRatio = 1.0;
  56934. _this.ignoreCameraViewport = true;
  56935. _this.onBeforeRenderObservable.add(function () {
  56936. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  56937. _this._savedViewMatrix = scene.getViewMatrix();
  56938. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  56939. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  56940. scene.clipPlane = _this.mirrorPlane;
  56941. scene.getEngine().cullBackFaces = false;
  56942. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  56943. });
  56944. _this.onAfterRenderObservable.add(function () {
  56945. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  56946. scene.getEngine().cullBackFaces = true;
  56947. scene._mirroredCameraPosition = null;
  56948. delete scene.clipPlane;
  56949. });
  56950. return _this;
  56951. }
  56952. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  56953. get: function () {
  56954. return this._blurRatio;
  56955. },
  56956. set: function (value) {
  56957. if (this._blurRatio === value) {
  56958. return;
  56959. }
  56960. this._blurRatio = value;
  56961. this._preparePostProcesses();
  56962. },
  56963. enumerable: true,
  56964. configurable: true
  56965. });
  56966. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  56967. set: function (value) {
  56968. this._adaptiveBlurKernel = value;
  56969. this._autoComputeBlurKernel();
  56970. },
  56971. enumerable: true,
  56972. configurable: true
  56973. });
  56974. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  56975. set: function (value) {
  56976. this.blurKernelX = value;
  56977. this.blurKernelY = value;
  56978. },
  56979. enumerable: true,
  56980. configurable: true
  56981. });
  56982. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  56983. get: function () {
  56984. return this._blurKernelX;
  56985. },
  56986. set: function (value) {
  56987. if (this._blurKernelX === value) {
  56988. return;
  56989. }
  56990. this._blurKernelX = value;
  56991. this._preparePostProcesses();
  56992. },
  56993. enumerable: true,
  56994. configurable: true
  56995. });
  56996. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  56997. get: function () {
  56998. return this._blurKernelY;
  56999. },
  57000. set: function (value) {
  57001. if (this._blurKernelY === value) {
  57002. return;
  57003. }
  57004. this._blurKernelY = value;
  57005. this._preparePostProcesses();
  57006. },
  57007. enumerable: true,
  57008. configurable: true
  57009. });
  57010. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  57011. var engine = this.getScene().getEngine();
  57012. var dw = this.getRenderWidth() / engine.getRenderWidth();
  57013. var dh = this.getRenderHeight() / engine.getRenderHeight();
  57014. this.blurKernelX = this._adaptiveBlurKernel * dw;
  57015. this.blurKernelY = this._adaptiveBlurKernel * dh;
  57016. };
  57017. MirrorTexture.prototype._onRatioRescale = function () {
  57018. if (this._sizeRatio) {
  57019. this.resize(this._initialSizeParameter);
  57020. if (!this._adaptiveBlurKernel) {
  57021. this._preparePostProcesses();
  57022. }
  57023. }
  57024. if (this._adaptiveBlurKernel) {
  57025. this._autoComputeBlurKernel();
  57026. }
  57027. };
  57028. MirrorTexture.prototype._preparePostProcesses = function () {
  57029. this.clearPostProcesses(true);
  57030. if (this._blurKernelX && this._blurKernelY) {
  57031. var engine = this.getScene().getEngine();
  57032. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57033. 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);
  57034. this._blurX.autoClear = false;
  57035. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  57036. this._blurX.inputTexture = this._texture;
  57037. }
  57038. else {
  57039. this._blurX.alwaysForcePOT = true;
  57040. }
  57041. 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);
  57042. this._blurY.autoClear = false;
  57043. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  57044. this.addPostProcess(this._blurX);
  57045. this.addPostProcess(this._blurY);
  57046. }
  57047. else {
  57048. if (this._blurY) {
  57049. this.removePostProcess(this._blurY);
  57050. this._blurY.dispose();
  57051. this._blurY = null;
  57052. }
  57053. if (this._blurX) {
  57054. this.removePostProcess(this._blurX);
  57055. this._blurX.dispose();
  57056. this._blurX = null;
  57057. }
  57058. }
  57059. };
  57060. MirrorTexture.prototype.clone = function () {
  57061. var scene = this.getScene();
  57062. if (!scene) {
  57063. return this;
  57064. }
  57065. var textureSize = this.getSize();
  57066. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  57067. // Base texture
  57068. newTexture.hasAlpha = this.hasAlpha;
  57069. newTexture.level = this.level;
  57070. // Mirror Texture
  57071. newTexture.mirrorPlane = this.mirrorPlane.clone();
  57072. if (this.renderList) {
  57073. newTexture.renderList = this.renderList.slice(0);
  57074. }
  57075. return newTexture;
  57076. };
  57077. MirrorTexture.prototype.serialize = function () {
  57078. if (!this.name) {
  57079. return null;
  57080. }
  57081. var serializationObject = _super.prototype.serialize.call(this);
  57082. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  57083. return serializationObject;
  57084. };
  57085. return MirrorTexture;
  57086. }(BABYLON.RenderTargetTexture));
  57087. BABYLON.MirrorTexture = MirrorTexture;
  57088. })(BABYLON || (BABYLON = {}));
  57089. //# sourceMappingURL=babylon.mirrorTexture.js.map
  57090. var BABYLON;
  57091. (function (BABYLON) {
  57092. /**
  57093. * Creates a refraction texture used by refraction channel of the standard material.
  57094. * @param name the texture name
  57095. * @param size size of the underlying texture
  57096. * @param scene root scene
  57097. */
  57098. var RefractionTexture = /** @class */ (function (_super) {
  57099. __extends(RefractionTexture, _super);
  57100. function RefractionTexture(name, size, scene, generateMipMaps) {
  57101. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  57102. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  57103. _this.depth = 2.0;
  57104. _this.onBeforeRenderObservable.add(function () {
  57105. scene.clipPlane = _this.refractionPlane;
  57106. });
  57107. _this.onAfterRenderObservable.add(function () {
  57108. delete scene.clipPlane;
  57109. });
  57110. return _this;
  57111. }
  57112. RefractionTexture.prototype.clone = function () {
  57113. var scene = this.getScene();
  57114. if (!scene) {
  57115. return this;
  57116. }
  57117. var textureSize = this.getSize();
  57118. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  57119. // Base texture
  57120. newTexture.hasAlpha = this.hasAlpha;
  57121. newTexture.level = this.level;
  57122. // Refraction Texture
  57123. newTexture.refractionPlane = this.refractionPlane.clone();
  57124. if (this.renderList) {
  57125. newTexture.renderList = this.renderList.slice(0);
  57126. }
  57127. newTexture.depth = this.depth;
  57128. return newTexture;
  57129. };
  57130. RefractionTexture.prototype.serialize = function () {
  57131. if (!this.name) {
  57132. return null;
  57133. }
  57134. var serializationObject = _super.prototype.serialize.call(this);
  57135. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  57136. serializationObject.depth = this.depth;
  57137. return serializationObject;
  57138. };
  57139. return RefractionTexture;
  57140. }(BABYLON.RenderTargetTexture));
  57141. BABYLON.RefractionTexture = RefractionTexture;
  57142. })(BABYLON || (BABYLON = {}));
  57143. //# sourceMappingURL=babylon.refractionTexture.js.map
  57144. var BABYLON;
  57145. (function (BABYLON) {
  57146. var DynamicTexture = /** @class */ (function (_super) {
  57147. __extends(DynamicTexture, _super);
  57148. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  57149. if (scene === void 0) { scene = null; }
  57150. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57151. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57152. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  57153. _this.name = name;
  57154. _this._engine = _this.getScene().getEngine();
  57155. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57156. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57157. _this._generateMipMaps = generateMipMaps;
  57158. if (options.getContext) {
  57159. _this._canvas = options;
  57160. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57161. }
  57162. else {
  57163. _this._canvas = document.createElement("canvas");
  57164. if (options.width) {
  57165. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57166. }
  57167. else {
  57168. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  57169. }
  57170. }
  57171. var textureSize = _this.getSize();
  57172. _this._canvas.width = textureSize.width;
  57173. _this._canvas.height = textureSize.height;
  57174. _this._context = _this._canvas.getContext("2d");
  57175. return _this;
  57176. }
  57177. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  57178. get: function () {
  57179. return true;
  57180. },
  57181. enumerable: true,
  57182. configurable: true
  57183. });
  57184. DynamicTexture.prototype._recreate = function (textureSize) {
  57185. this._canvas.width = textureSize.width;
  57186. this._canvas.height = textureSize.height;
  57187. this.releaseInternalTexture();
  57188. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  57189. };
  57190. DynamicTexture.prototype.scale = function (ratio) {
  57191. var textureSize = this.getSize();
  57192. textureSize.width *= ratio;
  57193. textureSize.height *= ratio;
  57194. this._recreate(textureSize);
  57195. };
  57196. DynamicTexture.prototype.scaleTo = function (width, height) {
  57197. var textureSize = this.getSize();
  57198. textureSize.width = width;
  57199. textureSize.height = height;
  57200. this._recreate(textureSize);
  57201. };
  57202. DynamicTexture.prototype.getContext = function () {
  57203. return this._context;
  57204. };
  57205. DynamicTexture.prototype.clear = function () {
  57206. var size = this.getSize();
  57207. this._context.fillRect(0, 0, size.width, size.height);
  57208. };
  57209. DynamicTexture.prototype.update = function (invertY) {
  57210. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  57211. };
  57212. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  57213. if (update === void 0) { update = true; }
  57214. var size = this.getSize();
  57215. if (clearColor) {
  57216. this._context.fillStyle = clearColor;
  57217. this._context.fillRect(0, 0, size.width, size.height);
  57218. }
  57219. this._context.font = font;
  57220. if (x === null || x === undefined) {
  57221. var textSize = this._context.measureText(text);
  57222. x = (size.width - textSize.width) / 2;
  57223. }
  57224. if (y === null || y === undefined) {
  57225. var fontSize = parseInt((font.replace(/\D/g, '')));
  57226. ;
  57227. y = (size.height / 2) + (fontSize / 3.65);
  57228. }
  57229. this._context.fillStyle = color;
  57230. this._context.fillText(text, x, y);
  57231. if (update) {
  57232. this.update(invertY);
  57233. }
  57234. };
  57235. DynamicTexture.prototype.clone = function () {
  57236. var scene = this.getScene();
  57237. if (!scene) {
  57238. return this;
  57239. }
  57240. var textureSize = this.getSize();
  57241. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  57242. // Base texture
  57243. newTexture.hasAlpha = this.hasAlpha;
  57244. newTexture.level = this.level;
  57245. // Dynamic Texture
  57246. newTexture.wrapU = this.wrapU;
  57247. newTexture.wrapV = this.wrapV;
  57248. return newTexture;
  57249. };
  57250. DynamicTexture.prototype._rebuild = function () {
  57251. this.update();
  57252. };
  57253. return DynamicTexture;
  57254. }(BABYLON.Texture));
  57255. BABYLON.DynamicTexture = DynamicTexture;
  57256. })(BABYLON || (BABYLON = {}));
  57257. //# sourceMappingURL=babylon.dynamicTexture.js.map
  57258. var BABYLON;
  57259. (function (BABYLON) {
  57260. var VideoTexture = /** @class */ (function (_super) {
  57261. __extends(VideoTexture, _super);
  57262. /**
  57263. * Creates a video texture.
  57264. * Sample : https://doc.babylonjs.com/how_to/video_texture
  57265. * @param {string | null} name optional name, will detect from video source, if not defined
  57266. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  57267. * @param {BABYLON.Scene} scene is obviously the current scene.
  57268. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  57269. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  57270. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  57271. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  57272. */
  57273. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  57274. if (generateMipMaps === void 0) { generateMipMaps = false; }
  57275. if (invertY === void 0) { invertY = false; }
  57276. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57277. if (settings === void 0) { settings = {
  57278. autoPlay: true,
  57279. loop: true,
  57280. autoUpdateTexture: true,
  57281. }; }
  57282. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57283. _this._createInternalTexture = function () {
  57284. if (_this._texture != null) {
  57285. return;
  57286. }
  57287. if (!_this._engine.needPOTTextures ||
  57288. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  57289. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57290. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57291. }
  57292. else {
  57293. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57294. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57295. _this._generateMipMaps = false;
  57296. }
  57297. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  57298. _this._texture.isReady = true;
  57299. _this._updateInternalTexture();
  57300. };
  57301. _this.reset = function () {
  57302. if (_this._texture == null) {
  57303. return;
  57304. }
  57305. _this._texture.dispose();
  57306. _this._texture = null;
  57307. };
  57308. _this._updateInternalTexture = function (e) {
  57309. if (_this._texture == null || !_this._texture.isReady) {
  57310. return;
  57311. }
  57312. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  57313. return;
  57314. }
  57315. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  57316. };
  57317. _this._engine = _this.getScene().getEngine();
  57318. _this._generateMipMaps = generateMipMaps;
  57319. _this._samplingMode = samplingMode;
  57320. _this.autoUpdateTexture = settings.autoUpdateTexture;
  57321. _this.name = name || _this._getName(src);
  57322. _this.video = _this._getVideo(src);
  57323. if (settings.autoPlay !== undefined) {
  57324. _this.video.autoplay = settings.autoPlay;
  57325. }
  57326. if (settings.loop !== undefined) {
  57327. _this.video.loop = settings.loop;
  57328. }
  57329. _this.video.addEventListener("canplay", _this._createInternalTexture);
  57330. _this.video.addEventListener("paused", _this._updateInternalTexture);
  57331. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  57332. _this.video.addEventListener("emptied", _this.reset);
  57333. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  57334. _this._createInternalTexture();
  57335. }
  57336. return _this;
  57337. }
  57338. VideoTexture.prototype._getName = function (src) {
  57339. if (src instanceof HTMLVideoElement) {
  57340. return src.currentSrc;
  57341. }
  57342. if (typeof src === "object") {
  57343. return src.toString();
  57344. }
  57345. return src;
  57346. };
  57347. ;
  57348. VideoTexture.prototype._getVideo = function (src) {
  57349. if (src instanceof HTMLVideoElement) {
  57350. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  57351. return src;
  57352. }
  57353. var video = document.createElement("video");
  57354. if (typeof src === "string") {
  57355. BABYLON.Tools.SetCorsBehavior(src, video);
  57356. video.src = src;
  57357. }
  57358. else {
  57359. BABYLON.Tools.SetCorsBehavior(src[0], video);
  57360. src.forEach(function (url) {
  57361. var source = document.createElement("source");
  57362. source.src = url;
  57363. video.appendChild(source);
  57364. });
  57365. }
  57366. return video;
  57367. };
  57368. ;
  57369. /**
  57370. * Internal method to initiate `update`.
  57371. */
  57372. VideoTexture.prototype._rebuild = function () {
  57373. this.update();
  57374. };
  57375. /**
  57376. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  57377. */
  57378. VideoTexture.prototype.update = function () {
  57379. if (!this.autoUpdateTexture) {
  57380. // Expecting user to call `updateTexture` manually
  57381. return;
  57382. }
  57383. this.updateTexture(true);
  57384. };
  57385. /**
  57386. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  57387. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  57388. */
  57389. VideoTexture.prototype.updateTexture = function (isVisible) {
  57390. if (!isVisible) {
  57391. return;
  57392. }
  57393. if (this.video.paused) {
  57394. return;
  57395. }
  57396. this._updateInternalTexture();
  57397. };
  57398. /**
  57399. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  57400. * @param url New url.
  57401. */
  57402. VideoTexture.prototype.updateURL = function (url) {
  57403. this.video.src = url;
  57404. };
  57405. VideoTexture.prototype.dispose = function () {
  57406. _super.prototype.dispose.call(this);
  57407. this.video.removeEventListener("canplay", this._createInternalTexture);
  57408. this.video.removeEventListener("paused", this._updateInternalTexture);
  57409. this.video.removeEventListener("seeked", this._updateInternalTexture);
  57410. this.video.removeEventListener("emptied", this.reset);
  57411. };
  57412. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  57413. var video = document.createElement("video");
  57414. var constraintsDeviceId;
  57415. if (constraints && constraints.deviceId) {
  57416. constraintsDeviceId = {
  57417. exact: constraints.deviceId,
  57418. };
  57419. }
  57420. navigator.getUserMedia =
  57421. navigator.getUserMedia ||
  57422. navigator.webkitGetUserMedia ||
  57423. navigator.mozGetUserMedia ||
  57424. navigator.msGetUserMedia;
  57425. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  57426. if (navigator.getUserMedia) {
  57427. navigator.getUserMedia({
  57428. video: {
  57429. deviceId: constraintsDeviceId,
  57430. width: {
  57431. min: (constraints && constraints.minWidth) || 256,
  57432. max: (constraints && constraints.maxWidth) || 640,
  57433. },
  57434. height: {
  57435. min: (constraints && constraints.minHeight) || 256,
  57436. max: (constraints && constraints.maxHeight) || 480,
  57437. },
  57438. },
  57439. }, function (stream) {
  57440. if (video.mozSrcObject !== undefined) {
  57441. // hack for Firefox < 19
  57442. video.mozSrcObject = stream;
  57443. }
  57444. else {
  57445. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  57446. }
  57447. video.play();
  57448. if (onReady) {
  57449. onReady(new VideoTexture("video", video, scene, true, true));
  57450. }
  57451. }, function (e) {
  57452. BABYLON.Tools.Error(e.name);
  57453. });
  57454. }
  57455. };
  57456. return VideoTexture;
  57457. }(BABYLON.Texture));
  57458. BABYLON.VideoTexture = VideoTexture;
  57459. })(BABYLON || (BABYLON = {}));
  57460. //# sourceMappingURL=babylon.videoTexture.js.map
  57461. var BABYLON;
  57462. (function (BABYLON) {
  57463. var RawTexture = /** @class */ (function (_super) {
  57464. __extends(RawTexture, _super);
  57465. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  57466. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57467. if (invertY === void 0) { invertY = false; }
  57468. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57469. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57470. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57471. _this.format = format;
  57472. _this._engine = scene.getEngine();
  57473. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  57474. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57475. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57476. return _this;
  57477. }
  57478. RawTexture.prototype.update = function (data) {
  57479. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  57480. };
  57481. // Statics
  57482. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57483. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57484. if (invertY === void 0) { invertY = false; }
  57485. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57486. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  57487. };
  57488. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57489. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57490. if (invertY === void 0) { invertY = false; }
  57491. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57492. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57493. };
  57494. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57495. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57496. if (invertY === void 0) { invertY = false; }
  57497. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57498. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57499. };
  57500. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57501. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57502. if (invertY === void 0) { invertY = false; }
  57503. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57504. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57505. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  57506. };
  57507. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57508. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57509. if (invertY === void 0) { invertY = false; }
  57510. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57511. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57512. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  57513. };
  57514. return RawTexture;
  57515. }(BABYLON.Texture));
  57516. BABYLON.RawTexture = RawTexture;
  57517. })(BABYLON || (BABYLON = {}));
  57518. //# sourceMappingURL=babylon.rawTexture.js.map
  57519. var BABYLON;
  57520. (function (BABYLON) {
  57521. /**
  57522. * PostProcess can be used to apply a shader to a texture after it has been rendered
  57523. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  57524. */
  57525. var PostProcess = /** @class */ (function () {
  57526. /**
  57527. * Creates a new instance of @see PostProcess
  57528. * @param name The name of the PostProcess.
  57529. * @param fragmentUrl The url of the fragment shader to be used.
  57530. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  57531. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  57532. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  57533. * @param camera The camera to apply the render pass to.
  57534. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  57535. * @param engine The engine which the post process will be applied. (default: current engine)
  57536. * @param reusable If the post process can be reused on the same frame. (default: false)
  57537. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  57538. * @param textureType Type of textures used when performing the post process. (default: 0)
  57539. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  57540. * @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
  57541. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  57542. */
  57543. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  57544. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  57545. if (defines === void 0) { defines = null; }
  57546. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57547. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  57548. if (blockCompilation === void 0) { blockCompilation = false; }
  57549. this.name = name;
  57550. /**
  57551. * Width of the texture to apply the post process on
  57552. */
  57553. this.width = -1;
  57554. /**
  57555. * Height of the texture to apply the post process on
  57556. */
  57557. this.height = -1;
  57558. /**
  57559. * If the buffer needs to be cleared before applying the post process. (default: true)
  57560. * Should be set to false if shader will overwrite all previous pixels.
  57561. */
  57562. this.autoClear = true;
  57563. /**
  57564. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  57565. */
  57566. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  57567. /**
  57568. * Animations to be used for the post processing
  57569. */
  57570. this.animations = new Array();
  57571. /**
  57572. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  57573. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  57574. */
  57575. this.enablePixelPerfectMode = false;
  57576. /**
  57577. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  57578. */
  57579. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  57580. /**
  57581. * Force textures to be a power of two (default: false)
  57582. */
  57583. this.alwaysForcePOT = false;
  57584. /**
  57585. * Number of sample textures (default: 1)
  57586. */
  57587. this.samples = 1;
  57588. /**
  57589. * Modify the scale of the post process to be the same as the viewport (default: false)
  57590. */
  57591. this.adaptScaleToCurrentViewport = false;
  57592. this._reusable = false;
  57593. /**
  57594. * Smart array of input and output textures for the post process.
  57595. */
  57596. this._textures = new BABYLON.SmartArray(2);
  57597. /**
  57598. * The index in _textures that corresponds to the output texture.
  57599. */
  57600. this._currentRenderTextureInd = 0;
  57601. this._scaleRatio = new BABYLON.Vector2(1, 1);
  57602. this._texelSize = BABYLON.Vector2.Zero();
  57603. // Events
  57604. /**
  57605. * An event triggered when the postprocess is activated.
  57606. * @type {BABYLON.Observable}
  57607. */
  57608. this.onActivateObservable = new BABYLON.Observable();
  57609. /**
  57610. * An event triggered when the postprocess changes its size.
  57611. * @type {BABYLON.Observable}
  57612. */
  57613. this.onSizeChangedObservable = new BABYLON.Observable();
  57614. /**
  57615. * An event triggered when the postprocess applies its effect.
  57616. * @type {BABYLON.Observable}
  57617. */
  57618. this.onApplyObservable = new BABYLON.Observable();
  57619. /**
  57620. * An event triggered before rendering the postprocess
  57621. * @type {BABYLON.Observable}
  57622. */
  57623. this.onBeforeRenderObservable = new BABYLON.Observable();
  57624. /**
  57625. * An event triggered after rendering the postprocess
  57626. * @type {BABYLON.Observable}
  57627. */
  57628. this.onAfterRenderObservable = new BABYLON.Observable();
  57629. if (camera != null) {
  57630. this._camera = camera;
  57631. this._scene = camera.getScene();
  57632. camera.attachPostProcess(this);
  57633. this._engine = this._scene.getEngine();
  57634. this._scene.postProcesses.push(this);
  57635. }
  57636. else if (engine) {
  57637. this._engine = engine;
  57638. this._engine.postProcesses.push(this);
  57639. }
  57640. this._options = options;
  57641. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  57642. this._reusable = reusable || false;
  57643. this._textureType = textureType;
  57644. this._samplers = samplers || [];
  57645. this._samplers.push("textureSampler");
  57646. this._fragmentUrl = fragmentUrl;
  57647. this._vertexUrl = vertexUrl;
  57648. this._parameters = parameters || [];
  57649. this._parameters.push("scale");
  57650. this._indexParameters = indexParameters;
  57651. if (!blockCompilation) {
  57652. this.updateEffect(defines);
  57653. }
  57654. }
  57655. Object.defineProperty(PostProcess.prototype, "onActivate", {
  57656. /**
  57657. * A function that is added to the onActivateObservable
  57658. */
  57659. set: function (callback) {
  57660. if (this._onActivateObserver) {
  57661. this.onActivateObservable.remove(this._onActivateObserver);
  57662. }
  57663. if (callback) {
  57664. this._onActivateObserver = this.onActivateObservable.add(callback);
  57665. }
  57666. },
  57667. enumerable: true,
  57668. configurable: true
  57669. });
  57670. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  57671. /**
  57672. * A function that is added to the onSizeChangedObservable
  57673. */
  57674. set: function (callback) {
  57675. if (this._onSizeChangedObserver) {
  57676. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  57677. }
  57678. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  57679. },
  57680. enumerable: true,
  57681. configurable: true
  57682. });
  57683. Object.defineProperty(PostProcess.prototype, "onApply", {
  57684. /**
  57685. * A function that is added to the onApplyObservable
  57686. */
  57687. set: function (callback) {
  57688. if (this._onApplyObserver) {
  57689. this.onApplyObservable.remove(this._onApplyObserver);
  57690. }
  57691. this._onApplyObserver = this.onApplyObservable.add(callback);
  57692. },
  57693. enumerable: true,
  57694. configurable: true
  57695. });
  57696. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  57697. /**
  57698. * A function that is added to the onBeforeRenderObservable
  57699. */
  57700. set: function (callback) {
  57701. if (this._onBeforeRenderObserver) {
  57702. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57703. }
  57704. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57705. },
  57706. enumerable: true,
  57707. configurable: true
  57708. });
  57709. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  57710. /**
  57711. * A function that is added to the onAfterRenderObservable
  57712. */
  57713. set: function (callback) {
  57714. if (this._onAfterRenderObserver) {
  57715. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57716. }
  57717. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57718. },
  57719. enumerable: true,
  57720. configurable: true
  57721. });
  57722. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  57723. /**
  57724. * 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
  57725. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  57726. */
  57727. get: function () {
  57728. return this._textures.data[this._currentRenderTextureInd];
  57729. },
  57730. set: function (value) {
  57731. this._forcedOutputTexture = value;
  57732. },
  57733. enumerable: true,
  57734. configurable: true
  57735. });
  57736. /**
  57737. * Gets the camera which post process is applied to.
  57738. * @returns The camera the post process is applied to.
  57739. */
  57740. PostProcess.prototype.getCamera = function () {
  57741. return this._camera;
  57742. };
  57743. Object.defineProperty(PostProcess.prototype, "texelSize", {
  57744. /**
  57745. * Gets the texel size of the postprocess.
  57746. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  57747. */
  57748. get: function () {
  57749. if (this._shareOutputWithPostProcess) {
  57750. return this._shareOutputWithPostProcess.texelSize;
  57751. }
  57752. if (this._forcedOutputTexture) {
  57753. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  57754. }
  57755. return this._texelSize;
  57756. },
  57757. enumerable: true,
  57758. configurable: true
  57759. });
  57760. /**
  57761. * Gets the engine which this post process belongs to.
  57762. * @returns The engine the post process was enabled with.
  57763. */
  57764. PostProcess.prototype.getEngine = function () {
  57765. return this._engine;
  57766. };
  57767. /**
  57768. * The effect that is created when initializing the post process.
  57769. * @returns The created effect corrisponding the the postprocess.
  57770. */
  57771. PostProcess.prototype.getEffect = function () {
  57772. return this._effect;
  57773. };
  57774. /**
  57775. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  57776. * @param postProcess The post process to share the output with.
  57777. * @returns This post process.
  57778. */
  57779. PostProcess.prototype.shareOutputWith = function (postProcess) {
  57780. this._disposeTextures();
  57781. this._shareOutputWithPostProcess = postProcess;
  57782. return this;
  57783. };
  57784. /**
  57785. * Updates the effect with the current post process compile time values and recompiles the shader.
  57786. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  57787. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  57788. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  57789. * @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
  57790. * @param onCompiled Called when the shader has been compiled.
  57791. * @param onError Called if there is an error when compiling a shader.
  57792. */
  57793. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  57794. if (defines === void 0) { defines = null; }
  57795. if (uniforms === void 0) { uniforms = null; }
  57796. if (samplers === void 0) { samplers = null; }
  57797. 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);
  57798. };
  57799. /**
  57800. * The post process is reusable if it can be used multiple times within one frame.
  57801. * @returns If the post process is reusable
  57802. */
  57803. PostProcess.prototype.isReusable = function () {
  57804. return this._reusable;
  57805. };
  57806. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  57807. PostProcess.prototype.markTextureDirty = function () {
  57808. this.width = -1;
  57809. };
  57810. /**
  57811. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  57812. * 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.
  57813. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  57814. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  57815. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  57816. */
  57817. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  57818. var _this = this;
  57819. if (sourceTexture === void 0) { sourceTexture = null; }
  57820. camera = camera || this._camera;
  57821. var scene = camera.getScene();
  57822. var engine = scene.getEngine();
  57823. var maxSize = engine.getCaps().maxTextureSize;
  57824. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  57825. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  57826. var desiredWidth = (this._options.width || requiredWidth);
  57827. var desiredHeight = this._options.height || requiredHeight;
  57828. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  57829. if (this.adaptScaleToCurrentViewport) {
  57830. var currentViewport = engine.currentViewport;
  57831. if (currentViewport) {
  57832. desiredWidth *= currentViewport.width;
  57833. desiredHeight *= currentViewport.height;
  57834. }
  57835. }
  57836. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  57837. if (!this._options.width) {
  57838. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  57839. }
  57840. if (!this._options.height) {
  57841. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  57842. }
  57843. }
  57844. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  57845. if (this._textures.length > 0) {
  57846. for (var i = 0; i < this._textures.length; i++) {
  57847. this._engine._releaseTexture(this._textures.data[i]);
  57848. }
  57849. this._textures.reset();
  57850. }
  57851. this.width = desiredWidth;
  57852. this.height = desiredHeight;
  57853. var textureSize = { width: this.width, height: this.height };
  57854. var textureOptions = {
  57855. generateMipMaps: false,
  57856. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  57857. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  57858. samplingMode: this.renderTargetSamplingMode,
  57859. type: this._textureType
  57860. };
  57861. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57862. if (this._reusable) {
  57863. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57864. }
  57865. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  57866. this.onSizeChangedObservable.notifyObservers(this);
  57867. }
  57868. this._textures.forEach(function (texture) {
  57869. if (texture.samples !== _this.samples) {
  57870. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  57871. }
  57872. });
  57873. }
  57874. var target;
  57875. if (this._shareOutputWithPostProcess) {
  57876. target = this._shareOutputWithPostProcess.inputTexture;
  57877. }
  57878. else if (this._forcedOutputTexture) {
  57879. target = this._forcedOutputTexture;
  57880. this.width = this._forcedOutputTexture.width;
  57881. this.height = this._forcedOutputTexture.height;
  57882. }
  57883. else {
  57884. target = this.inputTexture;
  57885. }
  57886. // Bind the input of this post process to be used as the output of the previous post process.
  57887. if (this.enablePixelPerfectMode) {
  57888. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  57889. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  57890. }
  57891. else {
  57892. this._scaleRatio.copyFromFloats(1, 1);
  57893. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  57894. }
  57895. this.onActivateObservable.notifyObservers(camera);
  57896. // Clear
  57897. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  57898. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  57899. }
  57900. if (this._reusable) {
  57901. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  57902. }
  57903. };
  57904. Object.defineProperty(PostProcess.prototype, "isSupported", {
  57905. /**
  57906. * If the post process is supported.
  57907. */
  57908. get: function () {
  57909. return this._effect.isSupported;
  57910. },
  57911. enumerable: true,
  57912. configurable: true
  57913. });
  57914. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  57915. /**
  57916. * The aspect ratio of the output texture.
  57917. */
  57918. get: function () {
  57919. if (this._shareOutputWithPostProcess) {
  57920. return this._shareOutputWithPostProcess.aspectRatio;
  57921. }
  57922. if (this._forcedOutputTexture) {
  57923. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  57924. }
  57925. return this.width / this.height;
  57926. },
  57927. enumerable: true,
  57928. configurable: true
  57929. });
  57930. /**
  57931. * Get a value indicating if the post-process is ready to be used
  57932. * @returns true if the post-process is ready (shader is compiled)
  57933. */
  57934. PostProcess.prototype.isReady = function () {
  57935. return this._effect && this._effect.isReady();
  57936. };
  57937. /**
  57938. * Binds all textures and uniforms to the shader, this will be run on every pass.
  57939. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  57940. */
  57941. PostProcess.prototype.apply = function () {
  57942. // Check
  57943. if (!this._effect || !this._effect.isReady())
  57944. return null;
  57945. // States
  57946. this._engine.enableEffect(this._effect);
  57947. this._engine.setState(false);
  57948. this._engine.setDepthBuffer(false);
  57949. this._engine.setDepthWrite(false);
  57950. // Alpha
  57951. this._engine.setAlphaMode(this.alphaMode);
  57952. if (this.alphaConstants) {
  57953. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  57954. }
  57955. // Bind the output texture of the preivous post process as the input to this post process.
  57956. var source;
  57957. if (this._shareOutputWithPostProcess) {
  57958. source = this._shareOutputWithPostProcess.inputTexture;
  57959. }
  57960. else if (this._forcedOutputTexture) {
  57961. source = this._forcedOutputTexture;
  57962. }
  57963. else {
  57964. source = this.inputTexture;
  57965. }
  57966. this._effect._bindTexture("textureSampler", source);
  57967. // Parameters
  57968. this._effect.setVector2("scale", this._scaleRatio);
  57969. this.onApplyObservable.notifyObservers(this._effect);
  57970. return this._effect;
  57971. };
  57972. PostProcess.prototype._disposeTextures = function () {
  57973. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  57974. return;
  57975. }
  57976. if (this._textures.length > 0) {
  57977. for (var i = 0; i < this._textures.length; i++) {
  57978. this._engine._releaseTexture(this._textures.data[i]);
  57979. }
  57980. }
  57981. this._textures.dispose();
  57982. };
  57983. /**
  57984. * Disposes the post process.
  57985. * @param camera The camera to dispose the post process on.
  57986. */
  57987. PostProcess.prototype.dispose = function (camera) {
  57988. camera = camera || this._camera;
  57989. this._disposeTextures();
  57990. if (this._scene) {
  57991. var index_1 = this._scene.postProcesses.indexOf(this);
  57992. if (index_1 !== -1) {
  57993. this._scene.postProcesses.splice(index_1, 1);
  57994. }
  57995. }
  57996. else {
  57997. var index_2 = this._engine.postProcesses.indexOf(this);
  57998. if (index_2 !== -1) {
  57999. this._engine.postProcesses.splice(index_2, 1);
  58000. }
  58001. }
  58002. if (!camera) {
  58003. return;
  58004. }
  58005. camera.detachPostProcess(this);
  58006. var index = camera._postProcesses.indexOf(this);
  58007. if (index === 0 && camera._postProcesses.length > 0) {
  58008. this._camera._postProcesses[0].markTextureDirty();
  58009. }
  58010. this.onActivateObservable.clear();
  58011. this.onAfterRenderObservable.clear();
  58012. this.onApplyObservable.clear();
  58013. this.onBeforeRenderObservable.clear();
  58014. this.onSizeChangedObservable.clear();
  58015. };
  58016. return PostProcess;
  58017. }());
  58018. BABYLON.PostProcess = PostProcess;
  58019. })(BABYLON || (BABYLON = {}));
  58020. //# sourceMappingURL=babylon.postProcess.js.map
  58021. var BABYLON;
  58022. (function (BABYLON) {
  58023. var PassPostProcess = /** @class */ (function (_super) {
  58024. __extends(PassPostProcess, _super);
  58025. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58026. if (camera === void 0) { camera = null; }
  58027. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58028. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  58029. }
  58030. return PassPostProcess;
  58031. }(BABYLON.PostProcess));
  58032. BABYLON.PassPostProcess = PassPostProcess;
  58033. })(BABYLON || (BABYLON = {}));
  58034. //# sourceMappingURL=babylon.passPostProcess.js.map
  58035. var __assign = (this && this.__assign) || Object.assign || function(t) {
  58036. for (var s, i = 1, n = arguments.length; i < n; i++) {
  58037. s = arguments[i];
  58038. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  58039. t[p] = s[p];
  58040. }
  58041. return t;
  58042. };
  58043. var BABYLON;
  58044. (function (BABYLON) {
  58045. /**
  58046. * Default implementation of @see IShadowGenerator.
  58047. * This is the main object responsible of generating shadows in the framework.
  58048. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  58049. */
  58050. var ShadowGenerator = /** @class */ (function () {
  58051. /**
  58052. * Creates a ShadowGenerator object.
  58053. * A ShadowGenerator is the required tool to use the shadows.
  58054. * Each light casting shadows needs to use its own ShadowGenerator.
  58055. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  58056. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  58057. * @param light The light object generating the shadows.
  58058. * @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.
  58059. */
  58060. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  58061. this._bias = 0.00005;
  58062. this._blurBoxOffset = 1;
  58063. this._blurScale = 2;
  58064. this._blurKernel = 1;
  58065. this._useKernelBlur = false;
  58066. this._filter = ShadowGenerator.FILTER_NONE;
  58067. this._darkness = 0;
  58068. this._transparencyShadow = false;
  58069. /**
  58070. * Controls the extent to which the shadows fade out at the edge of the frustum
  58071. * Used only by directionals and spots
  58072. */
  58073. this.frustumEdgeFalloff = 0;
  58074. /**
  58075. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  58076. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  58077. * It might on the other hand introduce peter panning.
  58078. */
  58079. this.forceBackFacesOnly = false;
  58080. this._lightDirection = BABYLON.Vector3.Zero();
  58081. this._viewMatrix = BABYLON.Matrix.Zero();
  58082. this._projectionMatrix = BABYLON.Matrix.Zero();
  58083. this._transformMatrix = BABYLON.Matrix.Zero();
  58084. this._currentFaceIndex = 0;
  58085. this._currentFaceIndexCache = 0;
  58086. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  58087. this._mapSize = mapSize;
  58088. this._light = light;
  58089. this._scene = light.getScene();
  58090. light._shadowGenerator = this;
  58091. // Texture type fallback from float to int if not supported.
  58092. var caps = this._scene.getEngine().getCaps();
  58093. if (!useFullFloatFirst) {
  58094. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58095. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58096. }
  58097. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58098. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58099. }
  58100. else {
  58101. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58102. }
  58103. }
  58104. else {
  58105. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58106. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58107. }
  58108. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58109. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58110. }
  58111. else {
  58112. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58113. }
  58114. }
  58115. this._initializeGenerator();
  58116. }
  58117. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  58118. /**
  58119. * Shadow generator mode None: no filtering applied.
  58120. */
  58121. get: function () {
  58122. return ShadowGenerator._FILTER_NONE;
  58123. },
  58124. enumerable: true,
  58125. configurable: true
  58126. });
  58127. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  58128. /**
  58129. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  58130. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  58131. */
  58132. get: function () {
  58133. return ShadowGenerator._FILTER_POISSONSAMPLING;
  58134. },
  58135. enumerable: true,
  58136. configurable: true
  58137. });
  58138. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  58139. /**
  58140. * Shadow generator mode ESM: Exponential Shadow Mapping.
  58141. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58142. */
  58143. get: function () {
  58144. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  58145. },
  58146. enumerable: true,
  58147. configurable: true
  58148. });
  58149. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  58150. /**
  58151. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  58152. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58153. */
  58154. get: function () {
  58155. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  58156. },
  58157. enumerable: true,
  58158. configurable: true
  58159. });
  58160. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  58161. /**
  58162. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  58163. * edge artifacts on steep falloff.
  58164. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58165. */
  58166. get: function () {
  58167. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58168. },
  58169. enumerable: true,
  58170. configurable: true
  58171. });
  58172. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  58173. /**
  58174. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  58175. * edge artifacts on steep falloff.
  58176. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58177. */
  58178. get: function () {
  58179. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58180. },
  58181. enumerable: true,
  58182. configurable: true
  58183. });
  58184. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  58185. /**
  58186. * Gets the bias: offset applied on the depth preventing acnea.
  58187. */
  58188. get: function () {
  58189. return this._bias;
  58190. },
  58191. /**
  58192. * Sets the bias: offset applied on the depth preventing acnea.
  58193. */
  58194. set: function (bias) {
  58195. this._bias = bias;
  58196. },
  58197. enumerable: true,
  58198. configurable: true
  58199. });
  58200. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  58201. /**
  58202. * Gets the blur box offset: offset applied during the blur pass.
  58203. * Only usefull if useKernelBlur = false
  58204. */
  58205. get: function () {
  58206. return this._blurBoxOffset;
  58207. },
  58208. /**
  58209. * Sets the blur box offset: offset applied during the blur pass.
  58210. * Only usefull if useKernelBlur = false
  58211. */
  58212. set: function (value) {
  58213. if (this._blurBoxOffset === value) {
  58214. return;
  58215. }
  58216. this._blurBoxOffset = value;
  58217. this._disposeBlurPostProcesses();
  58218. },
  58219. enumerable: true,
  58220. configurable: true
  58221. });
  58222. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  58223. /**
  58224. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  58225. * 2 means half of the size.
  58226. */
  58227. get: function () {
  58228. return this._blurScale;
  58229. },
  58230. /**
  58231. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  58232. * 2 means half of the size.
  58233. */
  58234. set: function (value) {
  58235. if (this._blurScale === value) {
  58236. return;
  58237. }
  58238. this._blurScale = value;
  58239. this._disposeBlurPostProcesses();
  58240. },
  58241. enumerable: true,
  58242. configurable: true
  58243. });
  58244. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  58245. /**
  58246. * Gets the blur kernel: kernel size of the blur pass.
  58247. * Only usefull if useKernelBlur = true
  58248. */
  58249. get: function () {
  58250. return this._blurKernel;
  58251. },
  58252. /**
  58253. * Sets the blur kernel: kernel size of the blur pass.
  58254. * Only usefull if useKernelBlur = true
  58255. */
  58256. set: function (value) {
  58257. if (this._blurKernel === value) {
  58258. return;
  58259. }
  58260. this._blurKernel = value;
  58261. this._disposeBlurPostProcesses();
  58262. },
  58263. enumerable: true,
  58264. configurable: true
  58265. });
  58266. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  58267. /**
  58268. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  58269. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58270. */
  58271. get: function () {
  58272. return this._useKernelBlur;
  58273. },
  58274. /**
  58275. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  58276. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58277. */
  58278. set: function (value) {
  58279. if (this._useKernelBlur === value) {
  58280. return;
  58281. }
  58282. this._useKernelBlur = value;
  58283. this._disposeBlurPostProcesses();
  58284. },
  58285. enumerable: true,
  58286. configurable: true
  58287. });
  58288. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  58289. /**
  58290. * Gets the depth scale used in ESM mode.
  58291. */
  58292. get: function () {
  58293. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  58294. },
  58295. /**
  58296. * Sets the depth scale used in ESM mode.
  58297. * This can override the scale stored on the light.
  58298. */
  58299. set: function (value) {
  58300. this._depthScale = value;
  58301. },
  58302. enumerable: true,
  58303. configurable: true
  58304. });
  58305. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  58306. /**
  58307. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  58308. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58309. */
  58310. get: function () {
  58311. return this._filter;
  58312. },
  58313. /**
  58314. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  58315. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58316. */
  58317. set: function (value) {
  58318. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  58319. if (this._light.needCube()) {
  58320. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58321. this.useExponentialShadowMap = true;
  58322. return;
  58323. }
  58324. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58325. this.useCloseExponentialShadowMap = true;
  58326. return;
  58327. }
  58328. }
  58329. if (this._filter === value) {
  58330. return;
  58331. }
  58332. this._filter = value;
  58333. this._disposeBlurPostProcesses();
  58334. this._applyFilterValues();
  58335. this._light._markMeshesAsLightDirty();
  58336. },
  58337. enumerable: true,
  58338. configurable: true
  58339. });
  58340. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  58341. /**
  58342. * Gets if the current filter is set to Poisson Sampling aka PCF.
  58343. */
  58344. get: function () {
  58345. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  58346. },
  58347. /**
  58348. * Sets the current filter to Poisson Sampling aka PCF.
  58349. */
  58350. set: function (value) {
  58351. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  58352. return;
  58353. }
  58354. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  58355. },
  58356. enumerable: true,
  58357. configurable: true
  58358. });
  58359. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  58360. /**
  58361. * Gets if the current filter is set to VSM.
  58362. * DEPRECATED. Should use useExponentialShadowMap instead.
  58363. */
  58364. get: function () {
  58365. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58366. return this.useExponentialShadowMap;
  58367. },
  58368. /**
  58369. * Sets the current filter is to VSM.
  58370. * DEPRECATED. Should use useExponentialShadowMap instead.
  58371. */
  58372. set: function (value) {
  58373. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58374. this.useExponentialShadowMap = value;
  58375. },
  58376. enumerable: true,
  58377. configurable: true
  58378. });
  58379. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  58380. /**
  58381. * Gets if the current filter is set to blurred VSM.
  58382. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58383. */
  58384. get: function () {
  58385. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58386. return this.useBlurExponentialShadowMap;
  58387. },
  58388. /**
  58389. * Sets the current filter is to blurred VSM.
  58390. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58391. */
  58392. set: function (value) {
  58393. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58394. this.useBlurExponentialShadowMap = value;
  58395. },
  58396. enumerable: true,
  58397. configurable: true
  58398. });
  58399. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  58400. /**
  58401. * Gets if the current filter is set to ESM.
  58402. */
  58403. get: function () {
  58404. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  58405. },
  58406. /**
  58407. * Sets the current filter is to ESM.
  58408. */
  58409. set: function (value) {
  58410. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  58411. return;
  58412. }
  58413. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58414. },
  58415. enumerable: true,
  58416. configurable: true
  58417. });
  58418. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  58419. /**
  58420. * Gets if the current filter is set to filtered ESM.
  58421. */
  58422. get: function () {
  58423. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  58424. },
  58425. /**
  58426. * Gets if the current filter is set to filtered ESM.
  58427. */
  58428. set: function (value) {
  58429. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58430. return;
  58431. }
  58432. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58433. },
  58434. enumerable: true,
  58435. configurable: true
  58436. });
  58437. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  58438. /**
  58439. * Gets if the current filter is set to "close ESM" (using the inverse of the
  58440. * exponential to prevent steep falloff artifacts).
  58441. */
  58442. get: function () {
  58443. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58444. },
  58445. /**
  58446. * Sets the current filter to "close ESM" (using the inverse of the
  58447. * exponential to prevent steep falloff artifacts).
  58448. */
  58449. set: function (value) {
  58450. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  58451. return;
  58452. }
  58453. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58454. },
  58455. enumerable: true,
  58456. configurable: true
  58457. });
  58458. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  58459. /**
  58460. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  58461. * exponential to prevent steep falloff artifacts).
  58462. */
  58463. get: function () {
  58464. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58465. },
  58466. /**
  58467. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  58468. * exponential to prevent steep falloff artifacts).
  58469. */
  58470. set: function (value) {
  58471. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58472. return;
  58473. }
  58474. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58475. },
  58476. enumerable: true,
  58477. configurable: true
  58478. });
  58479. /**
  58480. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  58481. * 0 means strongest and 1 would means no shadow.
  58482. * @returns the darkness.
  58483. */
  58484. ShadowGenerator.prototype.getDarkness = function () {
  58485. return this._darkness;
  58486. };
  58487. /**
  58488. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  58489. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  58490. * @returns the shadow generator allowing fluent coding.
  58491. */
  58492. ShadowGenerator.prototype.setDarkness = function (darkness) {
  58493. if (darkness >= 1.0)
  58494. this._darkness = 1.0;
  58495. else if (darkness <= 0.0)
  58496. this._darkness = 0.0;
  58497. else
  58498. this._darkness = darkness;
  58499. return this;
  58500. };
  58501. /**
  58502. * Sets the ability to have transparent shadow (boolean).
  58503. * @param transparent True if transparent else False
  58504. * @returns the shadow generator allowing fluent coding
  58505. */
  58506. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  58507. this._transparencyShadow = transparent;
  58508. return this;
  58509. };
  58510. /**
  58511. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  58512. * @returns The render target texture if present otherwise, null
  58513. */
  58514. ShadowGenerator.prototype.getShadowMap = function () {
  58515. return this._shadowMap;
  58516. };
  58517. /**
  58518. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  58519. * @returns The render target texture if the shadow map is present otherwise, null
  58520. */
  58521. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  58522. if (this._shadowMap2) {
  58523. return this._shadowMap2;
  58524. }
  58525. return this._shadowMap;
  58526. };
  58527. /**
  58528. * Helper function to add a mesh and its descendants to the list of shadow casters.
  58529. * @param mesh Mesh to add
  58530. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  58531. * @returns the Shadow Generator itself
  58532. */
  58533. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  58534. if (includeDescendants === void 0) { includeDescendants = true; }
  58535. if (!this._shadowMap) {
  58536. return this;
  58537. }
  58538. if (!this._shadowMap.renderList) {
  58539. this._shadowMap.renderList = [];
  58540. }
  58541. this._shadowMap.renderList.push(mesh);
  58542. if (includeDescendants) {
  58543. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  58544. }
  58545. return this;
  58546. var _a;
  58547. };
  58548. /**
  58549. * Helper function to remove a mesh and its descendants from the list of shadow casters
  58550. * @param mesh Mesh to remove
  58551. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  58552. * @returns the Shadow Generator itself
  58553. */
  58554. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  58555. if (includeDescendants === void 0) { includeDescendants = true; }
  58556. if (!this._shadowMap || !this._shadowMap.renderList) {
  58557. return this;
  58558. }
  58559. var index = this._shadowMap.renderList.indexOf(mesh);
  58560. if (index !== -1) {
  58561. this._shadowMap.renderList.splice(index, 1);
  58562. }
  58563. if (includeDescendants) {
  58564. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  58565. var child = _a[_i];
  58566. this.removeShadowCaster(child);
  58567. }
  58568. }
  58569. return this;
  58570. };
  58571. /**
  58572. * Returns the associated light object.
  58573. * @returns the light generating the shadow
  58574. */
  58575. ShadowGenerator.prototype.getLight = function () {
  58576. return this._light;
  58577. };
  58578. ShadowGenerator.prototype._initializeGenerator = function () {
  58579. this._light._markMeshesAsLightDirty();
  58580. this._initializeShadowMap();
  58581. };
  58582. ShadowGenerator.prototype._initializeShadowMap = function () {
  58583. var _this = this;
  58584. // Render target
  58585. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  58586. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58587. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58588. this._shadowMap.anisotropicFilteringLevel = 1;
  58589. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58590. this._shadowMap.renderParticles = false;
  58591. this._shadowMap.ignoreCameraViewport = true;
  58592. // Record Face Index before render.
  58593. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  58594. _this._currentFaceIndex = faceIndex;
  58595. });
  58596. // Custom render function.
  58597. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  58598. // Blur if required afer render.
  58599. this._shadowMap.onAfterUnbindObservable.add(function () {
  58600. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  58601. return;
  58602. }
  58603. var shadowMap = _this.getShadowMapForRendering();
  58604. if (shadowMap) {
  58605. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  58606. }
  58607. });
  58608. // Clear according to the chosen filter.
  58609. this._shadowMap.onClearObservable.add(function (engine) {
  58610. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  58611. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  58612. }
  58613. else {
  58614. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58615. }
  58616. });
  58617. };
  58618. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  58619. var _this = this;
  58620. var engine = this._scene.getEngine();
  58621. var targetSize = this._mapSize / this.blurScale;
  58622. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  58623. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  58624. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58625. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58626. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58627. }
  58628. if (this.useKernelBlur) {
  58629. 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);
  58630. this._kernelBlurXPostprocess.width = targetSize;
  58631. this._kernelBlurXPostprocess.height = targetSize;
  58632. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  58633. effect.setTexture("textureSampler", _this._shadowMap);
  58634. });
  58635. 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);
  58636. this._kernelBlurXPostprocess.autoClear = false;
  58637. this._kernelBlurYPostprocess.autoClear = false;
  58638. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58639. this._kernelBlurXPostprocess.packedFloat = true;
  58640. this._kernelBlurYPostprocess.packedFloat = true;
  58641. }
  58642. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  58643. }
  58644. else {
  58645. 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);
  58646. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  58647. effect.setFloat2("screenSize", targetSize, targetSize);
  58648. effect.setTexture("textureSampler", _this._shadowMap);
  58649. });
  58650. this._boxBlurPostprocess.autoClear = false;
  58651. this._blurPostProcesses = [this._boxBlurPostprocess];
  58652. }
  58653. };
  58654. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58655. var index;
  58656. var engine = this._scene.getEngine();
  58657. if (depthOnlySubMeshes.length) {
  58658. engine.setColorWrite(false);
  58659. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58660. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  58661. }
  58662. engine.setColorWrite(true);
  58663. }
  58664. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58665. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  58666. }
  58667. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58668. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  58669. }
  58670. if (this._transparencyShadow) {
  58671. for (index = 0; index < transparentSubMeshes.length; index++) {
  58672. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  58673. }
  58674. }
  58675. };
  58676. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  58677. var _this = this;
  58678. var mesh = subMesh.getRenderingMesh();
  58679. var scene = this._scene;
  58680. var engine = scene.getEngine();
  58681. var material = subMesh.getMaterial();
  58682. if (!material) {
  58683. return;
  58684. }
  58685. // Culling
  58686. engine.setState(material.backFaceCulling);
  58687. // Managing instances
  58688. var batch = mesh._getInstancesRenderList(subMesh._id);
  58689. if (batch.mustReturn) {
  58690. return;
  58691. }
  58692. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  58693. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  58694. engine.enableEffect(this._effect);
  58695. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  58696. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  58697. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  58698. this._effect.setVector3("lightPosition", this.getLight().position);
  58699. if (scene.activeCamera) {
  58700. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  58701. }
  58702. // Alpha test
  58703. if (material && material.needAlphaTesting()) {
  58704. var alphaTexture = material.getAlphaTestTexture();
  58705. if (alphaTexture) {
  58706. this._effect.setTexture("diffuseSampler", alphaTexture);
  58707. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  58708. }
  58709. }
  58710. // Bones
  58711. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58712. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  58713. }
  58714. if (this.forceBackFacesOnly) {
  58715. engine.setState(true, 0, false, true);
  58716. }
  58717. // Draw
  58718. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58719. if (this.forceBackFacesOnly) {
  58720. engine.setState(true, 0, false, false);
  58721. }
  58722. }
  58723. else {
  58724. // Need to reset refresh rate of the shadowMap
  58725. if (this._shadowMap) {
  58726. this._shadowMap.resetRefreshCounter();
  58727. }
  58728. }
  58729. };
  58730. ShadowGenerator.prototype._applyFilterValues = function () {
  58731. if (!this._shadowMap) {
  58732. return;
  58733. }
  58734. if (this.filter === ShadowGenerator.FILTER_NONE) {
  58735. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58736. }
  58737. else {
  58738. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58739. }
  58740. };
  58741. /**
  58742. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58743. * @param onCompiled Callback triggered at the and of the effects compilation
  58744. * @param options Sets of optional options forcing the compilation with different modes
  58745. */
  58746. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  58747. var _this = this;
  58748. var localOptions = __assign({ useInstances: false }, options);
  58749. var shadowMap = this.getShadowMap();
  58750. if (!shadowMap) {
  58751. if (onCompiled) {
  58752. onCompiled(this);
  58753. }
  58754. return;
  58755. }
  58756. var renderList = shadowMap.renderList;
  58757. if (!renderList) {
  58758. if (onCompiled) {
  58759. onCompiled(this);
  58760. }
  58761. return;
  58762. }
  58763. var subMeshes = new Array();
  58764. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  58765. var mesh = renderList_1[_i];
  58766. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  58767. }
  58768. if (subMeshes.length === 0) {
  58769. if (onCompiled) {
  58770. onCompiled(this);
  58771. }
  58772. return;
  58773. }
  58774. var currentIndex = 0;
  58775. var checkReady = function () {
  58776. if (!_this._scene || !_this._scene.getEngine()) {
  58777. return;
  58778. }
  58779. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  58780. currentIndex++;
  58781. if (currentIndex >= subMeshes.length) {
  58782. if (onCompiled) {
  58783. onCompiled(_this);
  58784. }
  58785. return;
  58786. }
  58787. }
  58788. setTimeout(checkReady, 16);
  58789. };
  58790. checkReady();
  58791. };
  58792. /**
  58793. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58794. * @param options Sets of optional options forcing the compilation with different modes
  58795. * @returns A promise that resolves when the compilation completes
  58796. */
  58797. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  58798. var _this = this;
  58799. return new Promise(function (resolve) {
  58800. _this.forceCompilation(function () {
  58801. resolve();
  58802. }, options);
  58803. });
  58804. };
  58805. /**
  58806. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  58807. * @param subMesh The submesh we want to render in the shadow map
  58808. * @param useInstances Defines wether will draw in the map using instances
  58809. * @returns true if ready otherwise, false
  58810. */
  58811. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  58812. var defines = [];
  58813. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58814. defines.push("#define FLOAT");
  58815. }
  58816. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58817. defines.push("#define ESM");
  58818. }
  58819. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58820. var mesh = subMesh.getMesh();
  58821. var material = subMesh.getMaterial();
  58822. // Alpha test
  58823. if (material && material.needAlphaTesting()) {
  58824. var alphaTexture = material.getAlphaTestTexture();
  58825. if (alphaTexture) {
  58826. defines.push("#define ALPHATEST");
  58827. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58828. attribs.push(BABYLON.VertexBuffer.UVKind);
  58829. defines.push("#define UV1");
  58830. }
  58831. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58832. if (alphaTexture.coordinatesIndex === 1) {
  58833. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58834. defines.push("#define UV2");
  58835. }
  58836. }
  58837. }
  58838. }
  58839. // Bones
  58840. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58841. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58842. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58843. if (mesh.numBoneInfluencers > 4) {
  58844. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58845. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58846. }
  58847. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58848. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58849. }
  58850. else {
  58851. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58852. }
  58853. // Instances
  58854. if (useInstances) {
  58855. defines.push("#define INSTANCES");
  58856. attribs.push("world0");
  58857. attribs.push("world1");
  58858. attribs.push("world2");
  58859. attribs.push("world3");
  58860. }
  58861. // Get correct effect
  58862. var join = defines.join("\n");
  58863. if (this._cachedDefines !== join) {
  58864. this._cachedDefines = join;
  58865. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  58866. }
  58867. if (!this._effect.isReady()) {
  58868. return false;
  58869. }
  58870. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58871. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  58872. this._initializeBlurRTTAndPostProcesses();
  58873. }
  58874. }
  58875. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  58876. return false;
  58877. }
  58878. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  58879. return false;
  58880. }
  58881. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  58882. return false;
  58883. }
  58884. return true;
  58885. };
  58886. /**
  58887. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  58888. * @param defines Defines of the material we want to update
  58889. * @param lightIndex Index of the light in the enabled light list of the material
  58890. */
  58891. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  58892. var scene = this._scene;
  58893. var light = this._light;
  58894. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58895. return;
  58896. }
  58897. defines["SHADOW" + lightIndex] = true;
  58898. if (this.usePoissonSampling) {
  58899. defines["SHADOWPCF" + lightIndex] = true;
  58900. }
  58901. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58902. defines["SHADOWESM" + lightIndex] = true;
  58903. }
  58904. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58905. defines["SHADOWCLOSEESM" + lightIndex] = true;
  58906. }
  58907. if (light.needCube()) {
  58908. defines["SHADOWCUBE" + lightIndex] = true;
  58909. }
  58910. };
  58911. /**
  58912. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  58913. * defined in the generator but impacting the effect).
  58914. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  58915. * @param effect The effect we are binfing the information for
  58916. */
  58917. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  58918. var light = this._light;
  58919. var scene = this._scene;
  58920. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58921. return;
  58922. }
  58923. var camera = scene.activeCamera;
  58924. if (!camera) {
  58925. return;
  58926. }
  58927. var shadowMap = this.getShadowMap();
  58928. if (!shadowMap) {
  58929. return;
  58930. }
  58931. if (!light.needCube()) {
  58932. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  58933. }
  58934. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  58935. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  58936. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  58937. };
  58938. /**
  58939. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  58940. * (eq to shadow prjection matrix * light transform matrix)
  58941. * @returns The transform matrix used to create the shadow map
  58942. */
  58943. ShadowGenerator.prototype.getTransformMatrix = function () {
  58944. var scene = this._scene;
  58945. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  58946. return this._transformMatrix;
  58947. }
  58948. this._currentRenderID = scene.getRenderId();
  58949. this._currentFaceIndexCache = this._currentFaceIndex;
  58950. var lightPosition = this._light.position;
  58951. if (this._light.computeTransformedInformation()) {
  58952. lightPosition = this._light.transformedPosition;
  58953. }
  58954. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  58955. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  58956. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  58957. }
  58958. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  58959. this._cachedPosition = lightPosition.clone();
  58960. this._cachedDirection = this._lightDirection.clone();
  58961. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  58962. var shadowMap = this.getShadowMap();
  58963. if (shadowMap) {
  58964. var renderList = shadowMap.renderList;
  58965. if (renderList) {
  58966. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  58967. }
  58968. }
  58969. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  58970. }
  58971. return this._transformMatrix;
  58972. };
  58973. /**
  58974. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  58975. * Cube and 2D textures for instance.
  58976. */
  58977. ShadowGenerator.prototype.recreateShadowMap = function () {
  58978. var shadowMap = this._shadowMap;
  58979. if (!shadowMap) {
  58980. return;
  58981. }
  58982. // Track render list.
  58983. var renderList = shadowMap.renderList;
  58984. // Clean up existing data.
  58985. this._disposeRTTandPostProcesses();
  58986. // Reinitializes.
  58987. this._initializeGenerator();
  58988. // Reaffect the filter to ensure a correct fallback if necessary.
  58989. this.filter = this.filter;
  58990. // Reaffect the filter.
  58991. this._applyFilterValues();
  58992. // Reaffect Render List.
  58993. this._shadowMap.renderList = renderList;
  58994. };
  58995. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  58996. if (this._shadowMap2) {
  58997. this._shadowMap2.dispose();
  58998. this._shadowMap2 = null;
  58999. }
  59000. if (this._boxBlurPostprocess) {
  59001. this._boxBlurPostprocess.dispose();
  59002. this._boxBlurPostprocess = null;
  59003. }
  59004. if (this._kernelBlurXPostprocess) {
  59005. this._kernelBlurXPostprocess.dispose();
  59006. this._kernelBlurXPostprocess = null;
  59007. }
  59008. if (this._kernelBlurYPostprocess) {
  59009. this._kernelBlurYPostprocess.dispose();
  59010. this._kernelBlurYPostprocess = null;
  59011. }
  59012. this._blurPostProcesses = [];
  59013. };
  59014. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  59015. if (this._shadowMap) {
  59016. this._shadowMap.dispose();
  59017. this._shadowMap = null;
  59018. }
  59019. this._disposeBlurPostProcesses();
  59020. };
  59021. /**
  59022. * Disposes the ShadowGenerator.
  59023. * Returns nothing.
  59024. */
  59025. ShadowGenerator.prototype.dispose = function () {
  59026. this._disposeRTTandPostProcesses();
  59027. if (this._light) {
  59028. this._light._shadowGenerator = null;
  59029. this._light._markMeshesAsLightDirty();
  59030. }
  59031. };
  59032. /**
  59033. * Serializes the shadow generator setup to a json object.
  59034. * @returns The serialized JSON object
  59035. */
  59036. ShadowGenerator.prototype.serialize = function () {
  59037. var serializationObject = {};
  59038. var shadowMap = this.getShadowMap();
  59039. if (!shadowMap) {
  59040. return serializationObject;
  59041. }
  59042. serializationObject.lightId = this._light.id;
  59043. serializationObject.mapSize = shadowMap.getRenderSize();
  59044. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  59045. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  59046. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59047. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59048. serializationObject.usePoissonSampling = this.usePoissonSampling;
  59049. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  59050. serializationObject.depthScale = this.depthScale;
  59051. serializationObject.darkness = this.getDarkness();
  59052. serializationObject.blurBoxOffset = this.blurBoxOffset;
  59053. serializationObject.blurKernel = this.blurKernel;
  59054. serializationObject.blurScale = this.blurScale;
  59055. serializationObject.useKernelBlur = this.useKernelBlur;
  59056. serializationObject.transparencyShadow = this._transparencyShadow;
  59057. serializationObject.renderList = [];
  59058. if (shadowMap.renderList) {
  59059. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  59060. var mesh = shadowMap.renderList[meshIndex];
  59061. serializationObject.renderList.push(mesh.id);
  59062. }
  59063. }
  59064. return serializationObject;
  59065. };
  59066. /**
  59067. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  59068. * @param parsedShadowGenerator The JSON object to parse
  59069. * @param scene The scene to create the shadow map for
  59070. * @returns The parsed shadow generator
  59071. */
  59072. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  59073. //casting to point light, as light is missing the position attr and typescript complains.
  59074. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  59075. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  59076. var shadowMap = shadowGenerator.getShadowMap();
  59077. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  59078. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  59079. meshes.forEach(function (mesh) {
  59080. if (!shadowMap) {
  59081. return;
  59082. }
  59083. if (!shadowMap.renderList) {
  59084. shadowMap.renderList = [];
  59085. }
  59086. shadowMap.renderList.push(mesh);
  59087. });
  59088. }
  59089. if (parsedShadowGenerator.usePoissonSampling) {
  59090. shadowGenerator.usePoissonSampling = true;
  59091. }
  59092. else if (parsedShadowGenerator.useExponentialShadowMap) {
  59093. shadowGenerator.useExponentialShadowMap = true;
  59094. }
  59095. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  59096. shadowGenerator.useBlurExponentialShadowMap = true;
  59097. }
  59098. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  59099. shadowGenerator.useCloseExponentialShadowMap = true;
  59100. }
  59101. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  59102. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  59103. }
  59104. else if (parsedShadowGenerator.useVarianceShadowMap) {
  59105. shadowGenerator.useExponentialShadowMap = true;
  59106. }
  59107. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  59108. shadowGenerator.useBlurExponentialShadowMap = true;
  59109. }
  59110. if (parsedShadowGenerator.depthScale) {
  59111. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  59112. }
  59113. if (parsedShadowGenerator.blurScale) {
  59114. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  59115. }
  59116. if (parsedShadowGenerator.blurBoxOffset) {
  59117. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  59118. }
  59119. if (parsedShadowGenerator.useKernelBlur) {
  59120. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  59121. }
  59122. if (parsedShadowGenerator.blurKernel) {
  59123. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  59124. }
  59125. if (parsedShadowGenerator.bias !== undefined) {
  59126. shadowGenerator.bias = parsedShadowGenerator.bias;
  59127. }
  59128. if (parsedShadowGenerator.darkness) {
  59129. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  59130. }
  59131. if (parsedShadowGenerator.transparencyShadow) {
  59132. shadowGenerator.setTransparencyShadow(true);
  59133. }
  59134. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  59135. return shadowGenerator;
  59136. };
  59137. ShadowGenerator._FILTER_NONE = 0;
  59138. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  59139. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  59140. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  59141. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  59142. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  59143. return ShadowGenerator;
  59144. }());
  59145. BABYLON.ShadowGenerator = ShadowGenerator;
  59146. })(BABYLON || (BABYLON = {}));
  59147. //# sourceMappingURL=babylon.shadowGenerator.js.map
  59148. var BABYLON;
  59149. (function (BABYLON) {
  59150. var DefaultLoadingScreen = /** @class */ (function () {
  59151. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  59152. if (_loadingText === void 0) { _loadingText = ""; }
  59153. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  59154. var _this = this;
  59155. this._renderingCanvas = _renderingCanvas;
  59156. this._loadingText = _loadingText;
  59157. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  59158. // Resize
  59159. this._resizeLoadingUI = function () {
  59160. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  59161. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  59162. if (!_this._loadingDiv) {
  59163. return;
  59164. }
  59165. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  59166. _this._loadingDiv.style.left = canvasRect.left + "px";
  59167. _this._loadingDiv.style.top = canvasRect.top + "px";
  59168. _this._loadingDiv.style.width = canvasRect.width + "px";
  59169. _this._loadingDiv.style.height = canvasRect.height + "px";
  59170. };
  59171. }
  59172. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  59173. if (this._loadingDiv) {
  59174. // Do not add a loading screen if there is already one
  59175. return;
  59176. }
  59177. this._loadingDiv = document.createElement("div");
  59178. this._loadingDiv.id = "babylonjsLoadingDiv";
  59179. this._loadingDiv.style.opacity = "0";
  59180. this._loadingDiv.style.transition = "opacity 1.5s ease";
  59181. this._loadingDiv.style.pointerEvents = "none";
  59182. // Loading text
  59183. this._loadingTextDiv = document.createElement("div");
  59184. this._loadingTextDiv.style.position = "absolute";
  59185. this._loadingTextDiv.style.left = "0";
  59186. this._loadingTextDiv.style.top = "50%";
  59187. this._loadingTextDiv.style.marginTop = "80px";
  59188. this._loadingTextDiv.style.width = "100%";
  59189. this._loadingTextDiv.style.height = "20px";
  59190. this._loadingTextDiv.style.fontFamily = "Arial";
  59191. this._loadingTextDiv.style.fontSize = "14px";
  59192. this._loadingTextDiv.style.color = "white";
  59193. this._loadingTextDiv.style.textAlign = "center";
  59194. this._loadingTextDiv.innerHTML = "Loading";
  59195. this._loadingDiv.appendChild(this._loadingTextDiv);
  59196. //set the predefined text
  59197. this._loadingTextDiv.innerHTML = this._loadingText;
  59198. // Generating keyframes
  59199. var style = document.createElement('style');
  59200. style.type = 'text/css';
  59201. 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 }";
  59202. style.innerHTML = keyFrames;
  59203. document.getElementsByTagName('head')[0].appendChild(style);
  59204. // Loading img
  59205. var imgBack = new Image();
  59206. 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";
  59207. imgBack.style.position = "absolute";
  59208. imgBack.style.left = "50%";
  59209. imgBack.style.top = "50%";
  59210. imgBack.style.marginLeft = "-60px";
  59211. imgBack.style.marginTop = "-60px";
  59212. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  59213. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  59214. imgBack.style.transformOrigin = "50% 50%";
  59215. imgBack.style.webkitTransformOrigin = "50% 50%";
  59216. this._loadingDiv.appendChild(imgBack);
  59217. this._resizeLoadingUI();
  59218. window.addEventListener("resize", this._resizeLoadingUI);
  59219. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59220. document.body.appendChild(this._loadingDiv);
  59221. this._loadingDiv.style.opacity = "1";
  59222. };
  59223. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  59224. var _this = this;
  59225. if (!this._loadingDiv) {
  59226. return;
  59227. }
  59228. var onTransitionEnd = function () {
  59229. if (!_this._loadingDiv) {
  59230. return;
  59231. }
  59232. document.body.removeChild(_this._loadingDiv);
  59233. window.removeEventListener("resize", _this._resizeLoadingUI);
  59234. _this._loadingDiv = null;
  59235. };
  59236. this._loadingDiv.style.opacity = "0";
  59237. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  59238. };
  59239. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  59240. set: function (text) {
  59241. this._loadingText = text;
  59242. if (this._loadingTextDiv) {
  59243. this._loadingTextDiv.innerHTML = this._loadingText;
  59244. }
  59245. },
  59246. enumerable: true,
  59247. configurable: true
  59248. });
  59249. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  59250. get: function () {
  59251. return this._loadingDivBackgroundColor;
  59252. },
  59253. set: function (color) {
  59254. this._loadingDivBackgroundColor = color;
  59255. if (!this._loadingDiv) {
  59256. return;
  59257. }
  59258. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59259. },
  59260. enumerable: true,
  59261. configurable: true
  59262. });
  59263. return DefaultLoadingScreen;
  59264. }());
  59265. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  59266. })(BABYLON || (BABYLON = {}));
  59267. //# sourceMappingURL=babylon.loadingScreen.js.map
  59268. var BABYLON;
  59269. (function (BABYLON) {
  59270. var SceneLoaderProgressEvent = /** @class */ (function () {
  59271. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  59272. this.lengthComputable = lengthComputable;
  59273. this.loaded = loaded;
  59274. this.total = total;
  59275. }
  59276. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  59277. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  59278. };
  59279. return SceneLoaderProgressEvent;
  59280. }());
  59281. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  59282. var SceneLoader = /** @class */ (function () {
  59283. function SceneLoader() {
  59284. }
  59285. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  59286. get: function () {
  59287. return 0;
  59288. },
  59289. enumerable: true,
  59290. configurable: true
  59291. });
  59292. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  59293. get: function () {
  59294. return 1;
  59295. },
  59296. enumerable: true,
  59297. configurable: true
  59298. });
  59299. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  59300. get: function () {
  59301. return 2;
  59302. },
  59303. enumerable: true,
  59304. configurable: true
  59305. });
  59306. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  59307. get: function () {
  59308. return 3;
  59309. },
  59310. enumerable: true,
  59311. configurable: true
  59312. });
  59313. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  59314. get: function () {
  59315. return SceneLoader._ForceFullSceneLoadingForIncremental;
  59316. },
  59317. set: function (value) {
  59318. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  59319. },
  59320. enumerable: true,
  59321. configurable: true
  59322. });
  59323. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  59324. get: function () {
  59325. return SceneLoader._ShowLoadingScreen;
  59326. },
  59327. set: function (value) {
  59328. SceneLoader._ShowLoadingScreen = value;
  59329. },
  59330. enumerable: true,
  59331. configurable: true
  59332. });
  59333. Object.defineProperty(SceneLoader, "loggingLevel", {
  59334. get: function () {
  59335. return SceneLoader._loggingLevel;
  59336. },
  59337. set: function (value) {
  59338. SceneLoader._loggingLevel = value;
  59339. },
  59340. enumerable: true,
  59341. configurable: true
  59342. });
  59343. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  59344. get: function () {
  59345. return SceneLoader._CleanBoneMatrixWeights;
  59346. },
  59347. set: function (value) {
  59348. SceneLoader._CleanBoneMatrixWeights = value;
  59349. },
  59350. enumerable: true,
  59351. configurable: true
  59352. });
  59353. SceneLoader._getDefaultPlugin = function () {
  59354. return SceneLoader._registeredPlugins[".babylon"];
  59355. };
  59356. SceneLoader._getPluginForExtension = function (extension) {
  59357. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  59358. if (registeredPlugin) {
  59359. return registeredPlugin;
  59360. }
  59361. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  59362. return SceneLoader._getDefaultPlugin();
  59363. };
  59364. SceneLoader._getPluginForDirectLoad = function (data) {
  59365. for (var extension in SceneLoader._registeredPlugins) {
  59366. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  59367. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  59368. return SceneLoader._registeredPlugins[extension];
  59369. }
  59370. }
  59371. return SceneLoader._getDefaultPlugin();
  59372. };
  59373. SceneLoader._getPluginForFilename = function (sceneFilename) {
  59374. if (sceneFilename.name) {
  59375. sceneFilename = sceneFilename.name;
  59376. }
  59377. var queryStringPosition = sceneFilename.indexOf("?");
  59378. if (queryStringPosition !== -1) {
  59379. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  59380. }
  59381. var dotPosition = sceneFilename.lastIndexOf(".");
  59382. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  59383. return SceneLoader._getPluginForExtension(extension);
  59384. };
  59385. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  59386. SceneLoader._getDirectLoad = function (sceneFilename) {
  59387. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  59388. return sceneFilename.substr(5);
  59389. }
  59390. return null;
  59391. };
  59392. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  59393. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  59394. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  59395. var plugin;
  59396. if (registeredPlugin.plugin.createPlugin) {
  59397. plugin = registeredPlugin.plugin.createPlugin();
  59398. }
  59399. else {
  59400. plugin = registeredPlugin.plugin;
  59401. }
  59402. var useArrayBuffer = registeredPlugin.isBinary;
  59403. var database;
  59404. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  59405. var dataCallback = function (data, responseURL) {
  59406. if (scene.isDisposed) {
  59407. onError("Scene has been disposed");
  59408. return;
  59409. }
  59410. scene.database = database;
  59411. onSuccess(plugin, data, responseURL);
  59412. };
  59413. var request = null;
  59414. var pluginDisposed = false;
  59415. var onDisposeObservable = plugin.onDisposeObservable;
  59416. if (onDisposeObservable) {
  59417. onDisposeObservable.add(function () {
  59418. pluginDisposed = true;
  59419. if (request) {
  59420. request.abort();
  59421. request = null;
  59422. }
  59423. onDispose();
  59424. });
  59425. }
  59426. var manifestChecked = function () {
  59427. if (pluginDisposed) {
  59428. return;
  59429. }
  59430. var url = rootUrl + sceneFilename;
  59431. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  59432. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  59433. } : undefined, database, useArrayBuffer, function (request, exception) {
  59434. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  59435. });
  59436. };
  59437. if (directLoad) {
  59438. dataCallback(directLoad);
  59439. return plugin;
  59440. }
  59441. if (rootUrl.indexOf("file:") === -1) {
  59442. if (scene.getEngine().enableOfflineSupport) {
  59443. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  59444. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  59445. }
  59446. else {
  59447. manifestChecked();
  59448. }
  59449. }
  59450. else {
  59451. var fileOrString = sceneFilename;
  59452. if (fileOrString.name) {
  59453. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  59454. }
  59455. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  59456. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  59457. }
  59458. else {
  59459. onError("Unable to find file named " + sceneFilename);
  59460. }
  59461. }
  59462. return plugin;
  59463. };
  59464. // Public functions
  59465. SceneLoader.GetPluginForExtension = function (extension) {
  59466. return SceneLoader._getPluginForExtension(extension).plugin;
  59467. };
  59468. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  59469. return !!SceneLoader._registeredPlugins[extension];
  59470. };
  59471. SceneLoader.RegisterPlugin = function (plugin) {
  59472. if (typeof plugin.extensions === "string") {
  59473. var extension = plugin.extensions;
  59474. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59475. plugin: plugin,
  59476. isBinary: false
  59477. };
  59478. }
  59479. else {
  59480. var extensions = plugin.extensions;
  59481. Object.keys(extensions).forEach(function (extension) {
  59482. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59483. plugin: plugin,
  59484. isBinary: extensions[extension].isBinary
  59485. };
  59486. });
  59487. }
  59488. };
  59489. /**
  59490. * Import meshes into a scene
  59491. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59492. * @param rootUrl a string that defines the root url for scene and resources
  59493. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59494. * @param scene the instance of BABYLON.Scene to append to
  59495. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  59496. * @param onProgress a callback with a progress event for each file being loaded
  59497. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59498. * @param pluginExtension the extension used to determine the plugin
  59499. * @returns The loaded plugin
  59500. */
  59501. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59502. if (onSuccess === void 0) { onSuccess = null; }
  59503. if (onProgress === void 0) { onProgress = null; }
  59504. if (onError === void 0) { onError = null; }
  59505. if (pluginExtension === void 0) { pluginExtension = null; }
  59506. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59507. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59508. return null;
  59509. }
  59510. var loadingToken = {};
  59511. scene._addPendingData(loadingToken);
  59512. var disposeHandler = function () {
  59513. scene._removePendingData(loadingToken);
  59514. };
  59515. var errorHandler = function (message, exception) {
  59516. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  59517. if (onError) {
  59518. onError(scene, errorMessage, exception);
  59519. }
  59520. else {
  59521. BABYLON.Tools.Error(errorMessage);
  59522. // should the exception be thrown?
  59523. }
  59524. disposeHandler();
  59525. };
  59526. var progressHandler = onProgress ? function (event) {
  59527. try {
  59528. onProgress(event);
  59529. }
  59530. catch (e) {
  59531. errorHandler("Error in onProgress callback", e);
  59532. }
  59533. } : undefined;
  59534. var successHandler = function (meshes, particleSystems, skeletons) {
  59535. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  59536. if (onSuccess) {
  59537. try {
  59538. onSuccess(meshes, particleSystems, skeletons);
  59539. }
  59540. catch (e) {
  59541. errorHandler("Error in onSuccess callback", e);
  59542. }
  59543. }
  59544. scene._removePendingData(loadingToken);
  59545. };
  59546. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59547. if (plugin.rewriteRootURL) {
  59548. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  59549. }
  59550. if (sceneFilename === "") {
  59551. if (sceneFilename === "") {
  59552. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59553. }
  59554. }
  59555. if (plugin.importMesh) {
  59556. var syncedPlugin = plugin;
  59557. var meshes = new Array();
  59558. var particleSystems = new Array();
  59559. var skeletons = new Array();
  59560. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  59561. return;
  59562. }
  59563. scene.loadingPluginName = plugin.name;
  59564. successHandler(meshes, particleSystems, skeletons);
  59565. }
  59566. else {
  59567. var asyncedPlugin = plugin;
  59568. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  59569. scene.loadingPluginName = plugin.name;
  59570. successHandler(result.meshes, result.particleSystems, result.skeletons);
  59571. }).catch(function (error) {
  59572. errorHandler(error.message, error);
  59573. });
  59574. }
  59575. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59576. };
  59577. /**
  59578. * Import meshes into a scene
  59579. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59580. * @param rootUrl a string that defines the root url for scene and resources
  59581. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59582. * @param scene the instance of BABYLON.Scene to append to
  59583. * @param onProgress a callback with a progress event for each file being loaded
  59584. * @param pluginExtension the extension used to determine the plugin
  59585. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  59586. */
  59587. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59588. if (onProgress === void 0) { onProgress = null; }
  59589. if (pluginExtension === void 0) { pluginExtension = null; }
  59590. return new Promise(function (resolve, reject) {
  59591. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  59592. resolve({
  59593. meshes: meshes,
  59594. particleSystems: particleSystems,
  59595. skeletons: skeletons
  59596. });
  59597. }, onProgress, function (scene, message, exception) {
  59598. reject(exception || new Error(message));
  59599. });
  59600. });
  59601. };
  59602. /**
  59603. * Load a scene
  59604. * @param rootUrl a string that defines the root url for scene and resources
  59605. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59606. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59607. * @param onSuccess a callback with the scene when import succeeds
  59608. * @param onProgress a callback with a progress event for each file being loaded
  59609. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59610. * @param pluginExtension the extension used to determine the plugin
  59611. * @returns The loaded plugin
  59612. */
  59613. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  59614. if (onSuccess === void 0) { onSuccess = null; }
  59615. if (onProgress === void 0) { onProgress = null; }
  59616. if (onError === void 0) { onError = null; }
  59617. if (pluginExtension === void 0) { pluginExtension = null; }
  59618. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  59619. };
  59620. /**
  59621. * Load a scene
  59622. * @param rootUrl a string that defines the root url for scene and resources
  59623. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59624. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59625. * @param onProgress a callback with a progress event for each file being loaded
  59626. * @param pluginExtension the extension used to determine the plugin
  59627. * @returns The loaded scene
  59628. */
  59629. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  59630. if (onProgress === void 0) { onProgress = null; }
  59631. if (pluginExtension === void 0) { pluginExtension = null; }
  59632. return new Promise(function (resolve, reject) {
  59633. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  59634. resolve(scene);
  59635. }, onProgress, function (scene, message, exception) {
  59636. reject(exception || new Error(message));
  59637. }, pluginExtension);
  59638. });
  59639. };
  59640. /**
  59641. * Append a scene
  59642. * @param rootUrl a string that defines the root url for scene and resources
  59643. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59644. * @param scene is the instance of BABYLON.Scene to append to
  59645. * @param onSuccess a callback with the scene when import succeeds
  59646. * @param onProgress a callback with a progress event for each file being loaded
  59647. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59648. * @param pluginExtension the extension used to determine the plugin
  59649. * @returns The loaded plugin
  59650. */
  59651. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59652. if (onSuccess === void 0) { onSuccess = null; }
  59653. if (onProgress === void 0) { onProgress = null; }
  59654. if (onError === void 0) { onError = null; }
  59655. if (pluginExtension === void 0) { pluginExtension = null; }
  59656. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59657. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59658. return null;
  59659. }
  59660. if (SceneLoader.ShowLoadingScreen) {
  59661. scene.getEngine().displayLoadingUI();
  59662. }
  59663. var loadingToken = {};
  59664. scene._addPendingData(loadingToken);
  59665. var disposeHandler = function () {
  59666. scene._removePendingData(loadingToken);
  59667. scene.getEngine().hideLoadingUI();
  59668. };
  59669. var errorHandler = function (message, exception) {
  59670. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59671. if (onError) {
  59672. onError(scene, errorMessage, exception);
  59673. }
  59674. else {
  59675. BABYLON.Tools.Error(errorMessage);
  59676. // should the exception be thrown?
  59677. }
  59678. disposeHandler();
  59679. };
  59680. var progressHandler = onProgress ? function (event) {
  59681. try {
  59682. onProgress(event);
  59683. }
  59684. catch (e) {
  59685. errorHandler("Error in onProgress callback", e);
  59686. }
  59687. } : undefined;
  59688. var successHandler = function () {
  59689. if (onSuccess) {
  59690. try {
  59691. onSuccess(scene);
  59692. }
  59693. catch (e) {
  59694. errorHandler("Error in onSuccess callback", e);
  59695. }
  59696. }
  59697. scene._removePendingData(loadingToken);
  59698. };
  59699. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59700. if (sceneFilename === "") {
  59701. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59702. }
  59703. if (plugin.load) {
  59704. var syncedPlugin = plugin;
  59705. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  59706. return;
  59707. }
  59708. scene.loadingPluginName = plugin.name;
  59709. successHandler();
  59710. }
  59711. else {
  59712. var asyncedPlugin = plugin;
  59713. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  59714. scene.loadingPluginName = plugin.name;
  59715. successHandler();
  59716. }).catch(function (error) {
  59717. errorHandler(error.message, error);
  59718. });
  59719. }
  59720. if (SceneLoader.ShowLoadingScreen) {
  59721. scene.executeWhenReady(function () {
  59722. scene.getEngine().hideLoadingUI();
  59723. });
  59724. }
  59725. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59726. };
  59727. /**
  59728. * Append a scene
  59729. * @param rootUrl a string that defines the root url for scene and resources
  59730. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59731. * @param scene is the instance of BABYLON.Scene to append to
  59732. * @param onProgress a callback with a progress event for each file being loaded
  59733. * @param pluginExtension the extension used to determine the plugin
  59734. * @returns The given scene
  59735. */
  59736. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59737. if (onProgress === void 0) { onProgress = null; }
  59738. if (pluginExtension === void 0) { pluginExtension = null; }
  59739. return new Promise(function (resolve, reject) {
  59740. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  59741. resolve(scene);
  59742. }, onProgress, function (scene, message, exception) {
  59743. reject(exception || new Error(message));
  59744. }, pluginExtension);
  59745. });
  59746. };
  59747. /**
  59748. * Load a scene into an asset container
  59749. * @param rootUrl a string that defines the root url for scene and resources
  59750. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59751. * @param scene is the instance of BABYLON.Scene to append to
  59752. * @param onSuccess a callback with the scene when import succeeds
  59753. * @param onProgress a callback with a progress event for each file being loaded
  59754. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59755. * @param pluginExtension the extension used to determine the plugin
  59756. * @returns The loaded plugin
  59757. */
  59758. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59759. if (onSuccess === void 0) { onSuccess = null; }
  59760. if (onProgress === void 0) { onProgress = null; }
  59761. if (onError === void 0) { onError = null; }
  59762. if (pluginExtension === void 0) { pluginExtension = null; }
  59763. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59764. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59765. return null;
  59766. }
  59767. var loadingToken = {};
  59768. scene._addPendingData(loadingToken);
  59769. var disposeHandler = function () {
  59770. scene._removePendingData(loadingToken);
  59771. };
  59772. var errorHandler = function (message, exception) {
  59773. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59774. if (onError) {
  59775. onError(scene, errorMessage, exception);
  59776. }
  59777. else {
  59778. BABYLON.Tools.Error(errorMessage);
  59779. // should the exception be thrown?
  59780. }
  59781. disposeHandler();
  59782. };
  59783. var progressHandler = onProgress ? function (event) {
  59784. try {
  59785. onProgress(event);
  59786. }
  59787. catch (e) {
  59788. errorHandler("Error in onProgress callback", e);
  59789. }
  59790. } : undefined;
  59791. var successHandler = function (assets) {
  59792. if (onSuccess) {
  59793. try {
  59794. onSuccess(assets);
  59795. }
  59796. catch (e) {
  59797. errorHandler("Error in onSuccess callback", e);
  59798. }
  59799. }
  59800. scene._removePendingData(loadingToken);
  59801. };
  59802. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59803. if (plugin.loadAssetContainer) {
  59804. var syncedPlugin = plugin;
  59805. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  59806. if (!assetContainer) {
  59807. return;
  59808. }
  59809. scene.loadingPluginName = plugin.name;
  59810. successHandler(assetContainer);
  59811. }
  59812. else if (plugin.loadAssetContainerAsync) {
  59813. var asyncedPlugin = plugin;
  59814. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  59815. scene.loadingPluginName = plugin.name;
  59816. successHandler(assetContainer);
  59817. }).catch(function (error) {
  59818. errorHandler(error.message, error);
  59819. });
  59820. }
  59821. else {
  59822. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  59823. }
  59824. if (SceneLoader.ShowLoadingScreen) {
  59825. scene.executeWhenReady(function () {
  59826. scene.getEngine().hideLoadingUI();
  59827. });
  59828. }
  59829. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59830. };
  59831. /**
  59832. * Load a scene into an asset container
  59833. * @param rootUrl a string that defines the root url for scene and resources
  59834. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59835. * @param scene is the instance of BABYLON.Scene to append to
  59836. * @param onProgress a callback with a progress event for each file being loaded
  59837. * @param pluginExtension the extension used to determine the plugin
  59838. * @returns The loaded asset container
  59839. */
  59840. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59841. if (onProgress === void 0) { onProgress = null; }
  59842. if (pluginExtension === void 0) { pluginExtension = null; }
  59843. return new Promise(function (resolve, reject) {
  59844. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  59845. resolve(assetContainer);
  59846. }, onProgress, function (scene, message, exception) {
  59847. reject(exception || new Error(message));
  59848. }, pluginExtension);
  59849. });
  59850. };
  59851. // Flags
  59852. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  59853. SceneLoader._ShowLoadingScreen = true;
  59854. SceneLoader._CleanBoneMatrixWeights = false;
  59855. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  59856. // Members
  59857. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  59858. SceneLoader._registeredPlugins = {};
  59859. return SceneLoader;
  59860. }());
  59861. BABYLON.SceneLoader = SceneLoader;
  59862. ;
  59863. })(BABYLON || (BABYLON = {}));
  59864. //# sourceMappingURL=babylon.sceneLoader.js.map
  59865. var BABYLON;
  59866. (function (BABYLON) {
  59867. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  59868. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59869. var parsedMaterial = parsedData.materials[index];
  59870. if (parsedMaterial.id === id) {
  59871. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59872. }
  59873. }
  59874. return null;
  59875. };
  59876. var isDescendantOf = function (mesh, names, hierarchyIds) {
  59877. for (var i in names) {
  59878. if (mesh.name === names[i]) {
  59879. hierarchyIds.push(mesh.id);
  59880. return true;
  59881. }
  59882. }
  59883. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  59884. hierarchyIds.push(mesh.id);
  59885. return true;
  59886. }
  59887. return false;
  59888. };
  59889. var logOperation = function (operation, producer) {
  59890. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  59891. };
  59892. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  59893. if (addToScene === void 0) { addToScene = false; }
  59894. var container = new BABYLON.AssetContainer(scene);
  59895. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  59896. // when SceneLoader.debugLogging = true (default), or exception encountered.
  59897. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  59898. // and avoid problems with multiple concurrent .babylon loads.
  59899. var log = "importScene has failed JSON parse";
  59900. try {
  59901. var parsedData = JSON.parse(data);
  59902. log = "";
  59903. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  59904. var index;
  59905. var cache;
  59906. // Lights
  59907. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  59908. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  59909. var parsedLight = parsedData.lights[index];
  59910. var light = BABYLON.Light.Parse(parsedLight, scene);
  59911. if (light) {
  59912. container.lights.push(light);
  59913. log += (index === 0 ? "\n\tLights:" : "");
  59914. log += "\n\t\t" + light.toString(fullDetails);
  59915. }
  59916. }
  59917. }
  59918. // Animations
  59919. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  59920. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  59921. var parsedAnimation = parsedData.animations[index];
  59922. var animation = BABYLON.Animation.Parse(parsedAnimation);
  59923. scene.animations.push(animation);
  59924. container.animations.push(animation);
  59925. log += (index === 0 ? "\n\tAnimations:" : "");
  59926. log += "\n\t\t" + animation.toString(fullDetails);
  59927. }
  59928. }
  59929. // Materials
  59930. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  59931. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59932. var parsedMaterial = parsedData.materials[index];
  59933. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59934. container.materials.push(mat);
  59935. log += (index === 0 ? "\n\tMaterials:" : "");
  59936. log += "\n\t\t" + mat.toString(fullDetails);
  59937. }
  59938. }
  59939. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  59940. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  59941. var parsedMultiMaterial = parsedData.multiMaterials[index];
  59942. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  59943. container.multiMaterials.push(mmat);
  59944. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  59945. log += "\n\t\t" + mmat.toString(fullDetails);
  59946. }
  59947. }
  59948. // Morph targets
  59949. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  59950. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  59951. var managerData = _a[_i];
  59952. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  59953. }
  59954. }
  59955. // Skeletons
  59956. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  59957. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  59958. var parsedSkeleton = parsedData.skeletons[index];
  59959. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  59960. container.skeletons.push(skeleton);
  59961. log += (index === 0 ? "\n\tSkeletons:" : "");
  59962. log += "\n\t\t" + skeleton.toString(fullDetails);
  59963. }
  59964. }
  59965. // Geometries
  59966. var geometries = parsedData.geometries;
  59967. if (geometries !== undefined && geometries !== null) {
  59968. var addedGeometry = new Array();
  59969. // Boxes
  59970. var boxes = geometries.boxes;
  59971. if (boxes !== undefined && boxes !== null) {
  59972. for (index = 0, cache = boxes.length; index < cache; index++) {
  59973. var parsedBox = boxes[index];
  59974. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  59975. }
  59976. }
  59977. // Spheres
  59978. var spheres = geometries.spheres;
  59979. if (spheres !== undefined && spheres !== null) {
  59980. for (index = 0, cache = spheres.length; index < cache; index++) {
  59981. var parsedSphere = spheres[index];
  59982. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  59983. }
  59984. }
  59985. // Cylinders
  59986. var cylinders = geometries.cylinders;
  59987. if (cylinders !== undefined && cylinders !== null) {
  59988. for (index = 0, cache = cylinders.length; index < cache; index++) {
  59989. var parsedCylinder = cylinders[index];
  59990. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  59991. }
  59992. }
  59993. // Toruses
  59994. var toruses = geometries.toruses;
  59995. if (toruses !== undefined && toruses !== null) {
  59996. for (index = 0, cache = toruses.length; index < cache; index++) {
  59997. var parsedTorus = toruses[index];
  59998. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  59999. }
  60000. }
  60001. // Grounds
  60002. var grounds = geometries.grounds;
  60003. if (grounds !== undefined && grounds !== null) {
  60004. for (index = 0, cache = grounds.length; index < cache; index++) {
  60005. var parsedGround = grounds[index];
  60006. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  60007. }
  60008. }
  60009. // Planes
  60010. var planes = geometries.planes;
  60011. if (planes !== undefined && planes !== null) {
  60012. for (index = 0, cache = planes.length; index < cache; index++) {
  60013. var parsedPlane = planes[index];
  60014. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  60015. }
  60016. }
  60017. // TorusKnots
  60018. var torusKnots = geometries.torusKnots;
  60019. if (torusKnots !== undefined && torusKnots !== null) {
  60020. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  60021. var parsedTorusKnot = torusKnots[index];
  60022. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  60023. }
  60024. }
  60025. // VertexData
  60026. var vertexData = geometries.vertexData;
  60027. if (vertexData !== undefined && vertexData !== null) {
  60028. for (index = 0, cache = vertexData.length; index < cache; index++) {
  60029. var parsedVertexData = vertexData[index];
  60030. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  60031. }
  60032. }
  60033. addedGeometry.forEach(function (g) {
  60034. if (g) {
  60035. container.geometries.push(g);
  60036. }
  60037. });
  60038. }
  60039. // Transform nodes
  60040. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  60041. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  60042. var parsedTransformNode = parsedData.transformNodes[index];
  60043. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  60044. container.transformNodes.push(node);
  60045. }
  60046. }
  60047. // Meshes
  60048. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60049. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60050. var parsedMesh = parsedData.meshes[index];
  60051. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60052. container.meshes.push(mesh);
  60053. log += (index === 0 ? "\n\tMeshes:" : "");
  60054. log += "\n\t\t" + mesh.toString(fullDetails);
  60055. }
  60056. }
  60057. // Cameras
  60058. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  60059. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  60060. var parsedCamera = parsedData.cameras[index];
  60061. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  60062. container.cameras.push(camera);
  60063. log += (index === 0 ? "\n\tCameras:" : "");
  60064. log += "\n\t\t" + camera.toString(fullDetails);
  60065. }
  60066. }
  60067. // Browsing all the graph to connect the dots
  60068. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  60069. var camera = scene.cameras[index];
  60070. if (camera._waitingParentId) {
  60071. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  60072. camera._waitingParentId = null;
  60073. }
  60074. }
  60075. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60076. var light_1 = scene.lights[index];
  60077. if (light_1 && light_1._waitingParentId) {
  60078. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  60079. light_1._waitingParentId = null;
  60080. }
  60081. }
  60082. // Sounds
  60083. // TODO: add sound
  60084. var loadedSounds = [];
  60085. var loadedSound;
  60086. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  60087. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  60088. var parsedSound = parsedData.sounds[index];
  60089. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60090. if (!parsedSound.url)
  60091. parsedSound.url = parsedSound.name;
  60092. if (!loadedSounds[parsedSound.url]) {
  60093. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  60094. loadedSounds[parsedSound.url] = loadedSound;
  60095. container.sounds.push(loadedSound);
  60096. }
  60097. else {
  60098. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  60099. }
  60100. }
  60101. else {
  60102. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  60103. }
  60104. }
  60105. }
  60106. loadedSounds = [];
  60107. // Connect parents & children and parse actions
  60108. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  60109. var transformNode = scene.transformNodes[index];
  60110. if (transformNode._waitingParentId) {
  60111. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  60112. transformNode._waitingParentId = null;
  60113. }
  60114. }
  60115. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60116. var mesh = scene.meshes[index];
  60117. if (mesh._waitingParentId) {
  60118. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  60119. mesh._waitingParentId = null;
  60120. }
  60121. if (mesh._waitingActions) {
  60122. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  60123. mesh._waitingActions = null;
  60124. }
  60125. }
  60126. // freeze world matrix application
  60127. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60128. var currentMesh = scene.meshes[index];
  60129. if (currentMesh._waitingFreezeWorldMatrix) {
  60130. currentMesh.freezeWorldMatrix();
  60131. currentMesh._waitingFreezeWorldMatrix = null;
  60132. }
  60133. else {
  60134. currentMesh.computeWorldMatrix(true);
  60135. }
  60136. }
  60137. // Particles Systems
  60138. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60139. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60140. var parsedParticleSystem = parsedData.particleSystems[index];
  60141. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60142. container.particleSystems.push(ps);
  60143. }
  60144. }
  60145. // Lens flares
  60146. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  60147. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  60148. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  60149. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  60150. container.lensFlareSystems.push(lf);
  60151. }
  60152. }
  60153. // Shadows
  60154. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  60155. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  60156. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  60157. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  60158. container.shadowGenerators.push(sg);
  60159. }
  60160. }
  60161. // Lights exclusions / inclusions
  60162. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60163. var light_2 = scene.lights[index];
  60164. // Excluded check
  60165. if (light_2._excludedMeshesIds.length > 0) {
  60166. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  60167. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  60168. if (excludedMesh) {
  60169. light_2.excludedMeshes.push(excludedMesh);
  60170. }
  60171. }
  60172. light_2._excludedMeshesIds = [];
  60173. }
  60174. // Included check
  60175. if (light_2._includedOnlyMeshesIds.length > 0) {
  60176. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  60177. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  60178. if (includedOnlyMesh) {
  60179. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  60180. }
  60181. }
  60182. light_2._includedOnlyMeshesIds = [];
  60183. }
  60184. }
  60185. // Actions (scene)
  60186. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  60187. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  60188. }
  60189. if (!addToScene) {
  60190. container.removeAllFromScene();
  60191. }
  60192. }
  60193. catch (err) {
  60194. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  60195. if (onError) {
  60196. onError(msg, err);
  60197. }
  60198. else {
  60199. BABYLON.Tools.Log(msg);
  60200. throw err;
  60201. }
  60202. }
  60203. finally {
  60204. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60205. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60206. }
  60207. }
  60208. return container;
  60209. };
  60210. BABYLON.SceneLoader.RegisterPlugin({
  60211. name: "babylon.js",
  60212. extensions: ".babylon",
  60213. canDirectLoad: function (data) {
  60214. if (data.indexOf("babylon") !== -1) {
  60215. return true;
  60216. }
  60217. return false;
  60218. },
  60219. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  60220. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60221. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60222. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60223. // and avoid problems with multiple concurrent .babylon loads.
  60224. var log = "importMesh has failed JSON parse";
  60225. try {
  60226. var parsedData = JSON.parse(data);
  60227. log = "";
  60228. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60229. if (!meshesNames) {
  60230. meshesNames = null;
  60231. }
  60232. else if (!Array.isArray(meshesNames)) {
  60233. meshesNames = [meshesNames];
  60234. }
  60235. var hierarchyIds = new Array();
  60236. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60237. var loadedSkeletonsIds = [];
  60238. var loadedMaterialsIds = [];
  60239. var index;
  60240. var cache;
  60241. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60242. var parsedMesh = parsedData.meshes[index];
  60243. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  60244. if (meshesNames !== null) {
  60245. // Remove found mesh name from list.
  60246. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  60247. }
  60248. //Geometry?
  60249. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  60250. //does the file contain geometries?
  60251. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  60252. //find the correct geometry and add it to the scene
  60253. var found = false;
  60254. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  60255. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  60256. return;
  60257. }
  60258. else {
  60259. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  60260. if (parsedGeometryData.id === parsedMesh.geometryId) {
  60261. switch (geometryType) {
  60262. case "boxes":
  60263. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  60264. break;
  60265. case "spheres":
  60266. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  60267. break;
  60268. case "cylinders":
  60269. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  60270. break;
  60271. case "toruses":
  60272. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  60273. break;
  60274. case "grounds":
  60275. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  60276. break;
  60277. case "planes":
  60278. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  60279. break;
  60280. case "torusKnots":
  60281. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  60282. break;
  60283. case "vertexData":
  60284. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  60285. break;
  60286. }
  60287. found = true;
  60288. }
  60289. });
  60290. }
  60291. });
  60292. if (found === false) {
  60293. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  60294. }
  60295. }
  60296. }
  60297. // Material ?
  60298. if (parsedMesh.materialId) {
  60299. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  60300. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60301. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  60302. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  60303. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  60304. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  60305. var subMatId = parsedMultiMaterial.materials[matIndex];
  60306. loadedMaterialsIds.push(subMatId);
  60307. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  60308. if (mat) {
  60309. log += "\n\tMaterial " + mat.toString(fullDetails);
  60310. }
  60311. }
  60312. loadedMaterialsIds.push(parsedMultiMaterial.id);
  60313. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60314. if (mmat) {
  60315. materialFound = true;
  60316. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  60317. }
  60318. break;
  60319. }
  60320. }
  60321. }
  60322. if (materialFound === false) {
  60323. loadedMaterialsIds.push(parsedMesh.materialId);
  60324. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  60325. if (!mat) {
  60326. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  60327. }
  60328. else {
  60329. log += "\n\tMaterial " + mat.toString(fullDetails);
  60330. }
  60331. }
  60332. }
  60333. // Skeleton ?
  60334. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60335. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  60336. if (skeletonAlreadyLoaded === false) {
  60337. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  60338. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  60339. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  60340. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60341. skeletons.push(skeleton);
  60342. loadedSkeletonsIds.push(parsedSkeleton.id);
  60343. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  60344. }
  60345. }
  60346. }
  60347. }
  60348. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60349. meshes.push(mesh);
  60350. log += "\n\tMesh " + mesh.toString(fullDetails);
  60351. }
  60352. }
  60353. // Connecting parents
  60354. var currentMesh;
  60355. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60356. currentMesh = scene.meshes[index];
  60357. if (currentMesh._waitingParentId) {
  60358. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  60359. currentMesh._waitingParentId = null;
  60360. }
  60361. }
  60362. // freeze and compute world matrix application
  60363. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60364. currentMesh = scene.meshes[index];
  60365. if (currentMesh._waitingFreezeWorldMatrix) {
  60366. currentMesh.freezeWorldMatrix();
  60367. currentMesh._waitingFreezeWorldMatrix = null;
  60368. }
  60369. else {
  60370. currentMesh.computeWorldMatrix(true);
  60371. }
  60372. }
  60373. }
  60374. // Particles
  60375. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60376. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60377. var parsedParticleSystem = parsedData.particleSystems[index];
  60378. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  60379. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  60380. }
  60381. }
  60382. }
  60383. return true;
  60384. }
  60385. catch (err) {
  60386. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  60387. if (onError) {
  60388. onError(msg, err);
  60389. }
  60390. else {
  60391. BABYLON.Tools.Log(msg);
  60392. throw err;
  60393. }
  60394. }
  60395. finally {
  60396. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60397. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60398. }
  60399. }
  60400. return false;
  60401. },
  60402. load: function (scene, data, rootUrl, onError) {
  60403. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60404. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60405. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60406. // and avoid problems with multiple concurrent .babylon loads.
  60407. var log = "importScene has failed JSON parse";
  60408. try {
  60409. var parsedData = JSON.parse(data);
  60410. log = "";
  60411. // Scene
  60412. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  60413. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  60414. }
  60415. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  60416. scene.autoClear = parsedData.autoClear;
  60417. }
  60418. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  60419. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  60420. }
  60421. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  60422. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  60423. }
  60424. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  60425. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  60426. }
  60427. // Fog
  60428. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  60429. scene.fogMode = parsedData.fogMode;
  60430. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  60431. scene.fogStart = parsedData.fogStart;
  60432. scene.fogEnd = parsedData.fogEnd;
  60433. scene.fogDensity = parsedData.fogDensity;
  60434. log += "\tFog mode for scene: ";
  60435. switch (scene.fogMode) {
  60436. // getters not compiling, so using hardcoded
  60437. case 1:
  60438. log += "exp\n";
  60439. break;
  60440. case 2:
  60441. log += "exp2\n";
  60442. break;
  60443. case 3:
  60444. log += "linear\n";
  60445. break;
  60446. }
  60447. }
  60448. //Physics
  60449. if (parsedData.physicsEnabled) {
  60450. var physicsPlugin;
  60451. if (parsedData.physicsEngine === "cannon") {
  60452. physicsPlugin = new BABYLON.CannonJSPlugin();
  60453. }
  60454. else if (parsedData.physicsEngine === "oimo") {
  60455. physicsPlugin = new BABYLON.OimoJSPlugin();
  60456. }
  60457. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  60458. //else - default engine, which is currently oimo
  60459. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  60460. scene.enablePhysics(physicsGravity, physicsPlugin);
  60461. }
  60462. // Metadata
  60463. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  60464. scene.metadata = parsedData.metadata;
  60465. }
  60466. //collisions, if defined. otherwise, default is true
  60467. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  60468. scene.collisionsEnabled = parsedData.collisionsEnabled;
  60469. }
  60470. scene.workerCollisions = !!parsedData.workerCollisions;
  60471. var container = loadAssetContainer(scene, data, rootUrl, onerror, true);
  60472. if (!container) {
  60473. return false;
  60474. }
  60475. if (parsedData.autoAnimate) {
  60476. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  60477. }
  60478. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  60479. scene.setActiveCameraByID(parsedData.activeCameraID);
  60480. }
  60481. // Environment texture
  60482. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  60483. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  60484. if (parsedData.createDefaultSkybox === true) {
  60485. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  60486. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  60487. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  60488. }
  60489. }
  60490. // Finish
  60491. return true;
  60492. }
  60493. catch (err) {
  60494. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  60495. if (onError) {
  60496. onError(msg, err);
  60497. }
  60498. else {
  60499. BABYLON.Tools.Log(msg);
  60500. throw err;
  60501. }
  60502. }
  60503. finally {
  60504. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60505. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60506. }
  60507. }
  60508. return false;
  60509. },
  60510. loadAssetContainer: function (scene, data, rootUrl, onError) {
  60511. var container = loadAssetContainer(scene, data, rootUrl, onerror);
  60512. return container;
  60513. }
  60514. });
  60515. })(BABYLON || (BABYLON = {}));
  60516. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  60517. var BABYLON;
  60518. (function (BABYLON) {
  60519. var FilesInput = /** @class */ (function () {
  60520. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  60521. this.onProcessFileCallback = function () { return true; };
  60522. this._engine = engine;
  60523. this._currentScene = scene;
  60524. this._sceneLoadedCallback = sceneLoadedCallback;
  60525. this._progressCallback = progressCallback;
  60526. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  60527. this._textureLoadingCallback = textureLoadingCallback;
  60528. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  60529. this._onReloadCallback = onReloadCallback;
  60530. this._errorCallback = errorCallback;
  60531. }
  60532. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  60533. var _this = this;
  60534. if (elementToMonitor) {
  60535. this._elementToMonitor = elementToMonitor;
  60536. this._dragEnterHandler = function (e) { _this.drag(e); };
  60537. this._dragOverHandler = function (e) { _this.drag(e); };
  60538. this._dropHandler = function (e) { _this.drop(e); };
  60539. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  60540. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  60541. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  60542. }
  60543. };
  60544. FilesInput.prototype.dispose = function () {
  60545. if (!this._elementToMonitor) {
  60546. return;
  60547. }
  60548. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  60549. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  60550. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  60551. };
  60552. FilesInput.prototype.renderFunction = function () {
  60553. if (this._additionalRenderLoopLogicCallback) {
  60554. this._additionalRenderLoopLogicCallback();
  60555. }
  60556. if (this._currentScene) {
  60557. if (this._textureLoadingCallback) {
  60558. var remaining = this._currentScene.getWaitingItemsCount();
  60559. if (remaining > 0) {
  60560. this._textureLoadingCallback(remaining);
  60561. }
  60562. }
  60563. this._currentScene.render();
  60564. }
  60565. };
  60566. FilesInput.prototype.drag = function (e) {
  60567. e.stopPropagation();
  60568. e.preventDefault();
  60569. };
  60570. FilesInput.prototype.drop = function (eventDrop) {
  60571. eventDrop.stopPropagation();
  60572. eventDrop.preventDefault();
  60573. this.loadFiles(eventDrop);
  60574. };
  60575. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  60576. var _this = this;
  60577. var reader = folder.createReader();
  60578. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  60579. reader.readEntries(function (entries) {
  60580. remaining.count += entries.length;
  60581. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  60582. var entry = entries_1[_i];
  60583. if (entry.isFile) {
  60584. entry.file(function (file) {
  60585. file.correctName = relativePath + file.name;
  60586. files.push(file);
  60587. if (--remaining.count === 0) {
  60588. callback();
  60589. }
  60590. });
  60591. }
  60592. else if (entry.isDirectory) {
  60593. _this._traverseFolder(entry, files, remaining, callback);
  60594. }
  60595. }
  60596. if (--remaining.count) {
  60597. callback();
  60598. }
  60599. });
  60600. };
  60601. FilesInput.prototype._processFiles = function (files) {
  60602. for (var i = 0; i < files.length; i++) {
  60603. var name = files[i].correctName.toLowerCase();
  60604. var extension = name.split('.').pop();
  60605. if (!this.onProcessFileCallback(files[i], name, extension)) {
  60606. continue;
  60607. }
  60608. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  60609. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  60610. this._sceneFileToLoad = files[i];
  60611. }
  60612. else {
  60613. FilesInput.FilesToLoad[name] = files[i];
  60614. }
  60615. }
  60616. };
  60617. FilesInput.prototype.loadFiles = function (event) {
  60618. var _this = this;
  60619. if (this._startingProcessingFilesCallback)
  60620. this._startingProcessingFilesCallback();
  60621. // Handling data transfer via drag'n'drop
  60622. if (event && event.dataTransfer && event.dataTransfer.files) {
  60623. this._filesToLoad = event.dataTransfer.files;
  60624. }
  60625. // Handling files from input files
  60626. if (event && event.target && event.target.files) {
  60627. this._filesToLoad = event.target.files;
  60628. }
  60629. if (this._filesToLoad && this._filesToLoad.length > 0) {
  60630. var files_1 = new Array();
  60631. var folders = [];
  60632. var items = event.dataTransfer ? event.dataTransfer.items : null;
  60633. for (var i = 0; i < this._filesToLoad.length; i++) {
  60634. var fileToLoad = this._filesToLoad[i];
  60635. var name_1 = fileToLoad.name.toLowerCase();
  60636. var entry = void 0;
  60637. fileToLoad.correctName = name_1;
  60638. if (items) {
  60639. var item = items[i];
  60640. if (item.getAsEntry) {
  60641. entry = item.getAsEntry();
  60642. }
  60643. else if (item.webkitGetAsEntry) {
  60644. entry = item.webkitGetAsEntry();
  60645. }
  60646. }
  60647. if (!entry) {
  60648. files_1.push(fileToLoad);
  60649. }
  60650. else {
  60651. if (entry.isDirectory) {
  60652. folders.push(entry);
  60653. }
  60654. else {
  60655. files_1.push(fileToLoad);
  60656. }
  60657. }
  60658. }
  60659. if (folders.length === 0) {
  60660. this._processFiles(files_1);
  60661. this._processReload();
  60662. }
  60663. else {
  60664. var remaining = { count: folders.length };
  60665. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  60666. var folder = folders_1[_i];
  60667. this._traverseFolder(folder, files_1, remaining, function () {
  60668. _this._processFiles(files_1);
  60669. if (remaining.count === 0) {
  60670. _this._processReload();
  60671. }
  60672. });
  60673. }
  60674. }
  60675. }
  60676. };
  60677. FilesInput.prototype._processReload = function () {
  60678. if (this._onReloadCallback) {
  60679. this._onReloadCallback(this._sceneFileToLoad);
  60680. }
  60681. else {
  60682. this.reload();
  60683. }
  60684. };
  60685. FilesInput.prototype.reload = function () {
  60686. var _this = this;
  60687. // If a scene file has been provided
  60688. if (this._sceneFileToLoad) {
  60689. if (this._currentScene) {
  60690. if (BABYLON.Tools.errorsCount > 0) {
  60691. BABYLON.Tools.ClearLogCache();
  60692. }
  60693. this._engine.stopRenderLoop();
  60694. this._currentScene.dispose();
  60695. }
  60696. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  60697. if (_this._progressCallback) {
  60698. _this._progressCallback(progress);
  60699. }
  60700. }).then(function (scene) {
  60701. _this._currentScene = scene;
  60702. if (_this._sceneLoadedCallback) {
  60703. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  60704. }
  60705. // Wait for textures and shaders to be ready
  60706. _this._currentScene.executeWhenReady(function () {
  60707. _this._engine.runRenderLoop(function () {
  60708. _this.renderFunction();
  60709. });
  60710. });
  60711. }).catch(function (error) {
  60712. if (_this._errorCallback) {
  60713. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  60714. }
  60715. });
  60716. }
  60717. else {
  60718. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  60719. }
  60720. };
  60721. FilesInput.FilesToLoad = {};
  60722. return FilesInput;
  60723. }());
  60724. BABYLON.FilesInput = FilesInput;
  60725. })(BABYLON || (BABYLON = {}));
  60726. //# sourceMappingURL=babylon.filesInput.js.map
  60727. var BABYLON;
  60728. (function (BABYLON) {
  60729. /**
  60730. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60731. * The underlying implementation relies on an associative array to ensure the best performances.
  60732. * The value can be anything including 'null' but except 'undefined'
  60733. */
  60734. var StringDictionary = /** @class */ (function () {
  60735. function StringDictionary() {
  60736. this._count = 0;
  60737. this._data = {};
  60738. }
  60739. /**
  60740. * This will clear this dictionary and copy the content from the 'source' one.
  60741. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60742. * @param source the dictionary to take the content from and copy to this dictionary
  60743. */
  60744. StringDictionary.prototype.copyFrom = function (source) {
  60745. var _this = this;
  60746. this.clear();
  60747. source.forEach(function (t, v) { return _this.add(t, v); });
  60748. };
  60749. /**
  60750. * Get a value based from its key
  60751. * @param key the given key to get the matching value from
  60752. * @return the value if found, otherwise undefined is returned
  60753. */
  60754. StringDictionary.prototype.get = function (key) {
  60755. var val = this._data[key];
  60756. if (val !== undefined) {
  60757. return val;
  60758. }
  60759. return undefined;
  60760. };
  60761. /**
  60762. * Get a value from its key or add it if it doesn't exist.
  60763. * This method will ensure you that a given key/data will be present in the dictionary.
  60764. * @param key the given key to get the matching value from
  60765. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60766. * The factory will only be invoked if there's no data for the given key.
  60767. * @return the value corresponding to the key.
  60768. */
  60769. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60770. var val = this.get(key);
  60771. if (val !== undefined) {
  60772. return val;
  60773. }
  60774. val = factory(key);
  60775. if (val) {
  60776. this.add(key, val);
  60777. }
  60778. return val;
  60779. };
  60780. /**
  60781. * Get a value from its key if present in the dictionary otherwise add it
  60782. * @param key the key to get the value from
  60783. * @param val if there's no such key/value pair in the dictionary add it with this value
  60784. * @return the value corresponding to the key
  60785. */
  60786. StringDictionary.prototype.getOrAdd = function (key, val) {
  60787. var curVal = this.get(key);
  60788. if (curVal !== undefined) {
  60789. return curVal;
  60790. }
  60791. this.add(key, val);
  60792. return val;
  60793. };
  60794. /**
  60795. * Check if there's a given key in the dictionary
  60796. * @param key the key to check for
  60797. * @return true if the key is present, false otherwise
  60798. */
  60799. StringDictionary.prototype.contains = function (key) {
  60800. return this._data[key] !== undefined;
  60801. };
  60802. /**
  60803. * Add a new key and its corresponding value
  60804. * @param key the key to add
  60805. * @param value the value corresponding to the key
  60806. * @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
  60807. */
  60808. StringDictionary.prototype.add = function (key, value) {
  60809. if (this._data[key] !== undefined) {
  60810. return false;
  60811. }
  60812. this._data[key] = value;
  60813. ++this._count;
  60814. return true;
  60815. };
  60816. StringDictionary.prototype.set = function (key, value) {
  60817. if (this._data[key] === undefined) {
  60818. return false;
  60819. }
  60820. this._data[key] = value;
  60821. return true;
  60822. };
  60823. /**
  60824. * Get the element of the given key and remove it from the dictionary
  60825. * @param key
  60826. */
  60827. StringDictionary.prototype.getAndRemove = function (key) {
  60828. var val = this.get(key);
  60829. if (val !== undefined) {
  60830. delete this._data[key];
  60831. --this._count;
  60832. return val;
  60833. }
  60834. return null;
  60835. };
  60836. /**
  60837. * Remove a key/value from the dictionary.
  60838. * @param key the key to remove
  60839. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60840. */
  60841. StringDictionary.prototype.remove = function (key) {
  60842. if (this.contains(key)) {
  60843. delete this._data[key];
  60844. --this._count;
  60845. return true;
  60846. }
  60847. return false;
  60848. };
  60849. /**
  60850. * Clear the whole content of the dictionary
  60851. */
  60852. StringDictionary.prototype.clear = function () {
  60853. this._data = {};
  60854. this._count = 0;
  60855. };
  60856. Object.defineProperty(StringDictionary.prototype, "count", {
  60857. get: function () {
  60858. return this._count;
  60859. },
  60860. enumerable: true,
  60861. configurable: true
  60862. });
  60863. /**
  60864. * Execute a callback on each key/val of the dictionary.
  60865. * Note that you can remove any element in this dictionary in the callback implementation
  60866. * @param callback the callback to execute on a given key/value pair
  60867. */
  60868. StringDictionary.prototype.forEach = function (callback) {
  60869. for (var cur in this._data) {
  60870. var val = this._data[cur];
  60871. callback(cur, val);
  60872. }
  60873. };
  60874. /**
  60875. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60876. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60877. * Note that you can remove any element in this dictionary in the callback implementation
  60878. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60879. */
  60880. StringDictionary.prototype.first = function (callback) {
  60881. for (var cur in this._data) {
  60882. var val = this._data[cur];
  60883. var res = callback(cur, val);
  60884. if (res) {
  60885. return res;
  60886. }
  60887. }
  60888. return null;
  60889. };
  60890. return StringDictionary;
  60891. }());
  60892. BABYLON.StringDictionary = StringDictionary;
  60893. })(BABYLON || (BABYLON = {}));
  60894. //# sourceMappingURL=babylon.stringDictionary.js.map
  60895. var BABYLON;
  60896. (function (BABYLON) {
  60897. var Tags = /** @class */ (function () {
  60898. function Tags() {
  60899. }
  60900. Tags.EnableFor = function (obj) {
  60901. obj._tags = obj._tags || {};
  60902. obj.hasTags = function () {
  60903. return Tags.HasTags(obj);
  60904. };
  60905. obj.addTags = function (tagsString) {
  60906. return Tags.AddTagsTo(obj, tagsString);
  60907. };
  60908. obj.removeTags = function (tagsString) {
  60909. return Tags.RemoveTagsFrom(obj, tagsString);
  60910. };
  60911. obj.matchesTagsQuery = function (tagsQuery) {
  60912. return Tags.MatchesQuery(obj, tagsQuery);
  60913. };
  60914. };
  60915. Tags.DisableFor = function (obj) {
  60916. delete obj._tags;
  60917. delete obj.hasTags;
  60918. delete obj.addTags;
  60919. delete obj.removeTags;
  60920. delete obj.matchesTagsQuery;
  60921. };
  60922. Tags.HasTags = function (obj) {
  60923. if (!obj._tags) {
  60924. return false;
  60925. }
  60926. return !BABYLON.Tools.IsEmpty(obj._tags);
  60927. };
  60928. Tags.GetTags = function (obj, asString) {
  60929. if (asString === void 0) { asString = true; }
  60930. if (!obj._tags) {
  60931. return null;
  60932. }
  60933. if (asString) {
  60934. var tagsArray = [];
  60935. for (var tag in obj._tags) {
  60936. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  60937. tagsArray.push(tag);
  60938. }
  60939. }
  60940. return tagsArray.join(" ");
  60941. }
  60942. else {
  60943. return obj._tags;
  60944. }
  60945. };
  60946. // the tags 'true' and 'false' are reserved and cannot be used as tags
  60947. // a tag cannot start with '||', '&&', and '!'
  60948. // it cannot contain whitespaces
  60949. Tags.AddTagsTo = function (obj, tagsString) {
  60950. if (!tagsString) {
  60951. return;
  60952. }
  60953. if (typeof tagsString !== "string") {
  60954. return;
  60955. }
  60956. var tags = tagsString.split(" ");
  60957. tags.forEach(function (tag, index, array) {
  60958. Tags._AddTagTo(obj, tag);
  60959. });
  60960. };
  60961. Tags._AddTagTo = function (obj, tag) {
  60962. tag = tag.trim();
  60963. if (tag === "" || tag === "true" || tag === "false") {
  60964. return;
  60965. }
  60966. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  60967. return;
  60968. }
  60969. Tags.EnableFor(obj);
  60970. obj._tags[tag] = true;
  60971. };
  60972. Tags.RemoveTagsFrom = function (obj, tagsString) {
  60973. if (!Tags.HasTags(obj)) {
  60974. return;
  60975. }
  60976. var tags = tagsString.split(" ");
  60977. for (var t in tags) {
  60978. Tags._RemoveTagFrom(obj, tags[t]);
  60979. }
  60980. };
  60981. Tags._RemoveTagFrom = function (obj, tag) {
  60982. delete obj._tags[tag];
  60983. };
  60984. Tags.MatchesQuery = function (obj, tagsQuery) {
  60985. if (tagsQuery === undefined) {
  60986. return true;
  60987. }
  60988. if (tagsQuery === "") {
  60989. return Tags.HasTags(obj);
  60990. }
  60991. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  60992. };
  60993. return Tags;
  60994. }());
  60995. BABYLON.Tags = Tags;
  60996. })(BABYLON || (BABYLON = {}));
  60997. //# sourceMappingURL=babylon.tags.js.map
  60998. var BABYLON;
  60999. (function (BABYLON) {
  61000. var AndOrNotEvaluator = /** @class */ (function () {
  61001. function AndOrNotEvaluator() {
  61002. }
  61003. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  61004. if (!query.match(/\([^\(\)]*\)/g)) {
  61005. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  61006. }
  61007. else {
  61008. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  61009. // remove parenthesis
  61010. r = r.slice(1, r.length - 1);
  61011. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  61012. });
  61013. }
  61014. if (query === "true") {
  61015. return true;
  61016. }
  61017. if (query === "false") {
  61018. return false;
  61019. }
  61020. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  61021. };
  61022. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  61023. evaluateCallback = evaluateCallback || (function (r) {
  61024. return r === "true" ? true : false;
  61025. });
  61026. var result;
  61027. var or = parenthesisContent.split("||");
  61028. for (var i in or) {
  61029. if (or.hasOwnProperty(i)) {
  61030. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  61031. var and = ori.split("&&");
  61032. if (and.length > 1) {
  61033. for (var j = 0; j < and.length; ++j) {
  61034. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  61035. if (andj !== "true" && andj !== "false") {
  61036. if (andj[0] === "!") {
  61037. result = !evaluateCallback(andj.substring(1));
  61038. }
  61039. else {
  61040. result = evaluateCallback(andj);
  61041. }
  61042. }
  61043. else {
  61044. result = andj === "true" ? true : false;
  61045. }
  61046. if (!result) {
  61047. ori = "false";
  61048. break;
  61049. }
  61050. }
  61051. }
  61052. if (result || ori === "true") {
  61053. result = true;
  61054. break;
  61055. }
  61056. // result equals false (or undefined)
  61057. if (ori !== "true" && ori !== "false") {
  61058. if (ori[0] === "!") {
  61059. result = !evaluateCallback(ori.substring(1));
  61060. }
  61061. else {
  61062. result = evaluateCallback(ori);
  61063. }
  61064. }
  61065. else {
  61066. result = ori === "true" ? true : false;
  61067. }
  61068. }
  61069. }
  61070. // the whole parenthesis scope is replaced by 'true' or 'false'
  61071. return result ? "true" : "false";
  61072. };
  61073. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  61074. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  61075. // remove whitespaces
  61076. r = r.replace(/[\s]/g, function () { return ""; });
  61077. return r.length % 2 ? "!" : "";
  61078. });
  61079. booleanString = booleanString.trim();
  61080. if (booleanString === "!true") {
  61081. booleanString = "false";
  61082. }
  61083. else if (booleanString === "!false") {
  61084. booleanString = "true";
  61085. }
  61086. return booleanString;
  61087. };
  61088. return AndOrNotEvaluator;
  61089. }());
  61090. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  61091. })(BABYLON || (BABYLON = {}));
  61092. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  61093. var BABYLON;
  61094. (function (BABYLON) {
  61095. var Database = /** @class */ (function () {
  61096. function Database(urlToScene, callbackManifestChecked) {
  61097. // Handling various flavors of prefixed version of IndexedDB
  61098. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  61099. this.callbackManifestChecked = callbackManifestChecked;
  61100. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  61101. this.db = null;
  61102. this._enableSceneOffline = false;
  61103. this._enableTexturesOffline = false;
  61104. this.manifestVersionFound = 0;
  61105. this.mustUpdateRessources = false;
  61106. this.hasReachedQuota = false;
  61107. if (!Database.IDBStorageEnabled) {
  61108. this.callbackManifestChecked(true);
  61109. }
  61110. else {
  61111. this.checkManifestFile();
  61112. }
  61113. }
  61114. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  61115. get: function () {
  61116. return this._enableSceneOffline;
  61117. },
  61118. enumerable: true,
  61119. configurable: true
  61120. });
  61121. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  61122. get: function () {
  61123. return this._enableTexturesOffline;
  61124. },
  61125. enumerable: true,
  61126. configurable: true
  61127. });
  61128. Database.prototype.checkManifestFile = function () {
  61129. var _this = this;
  61130. var noManifestFile = function () {
  61131. _this._enableSceneOffline = false;
  61132. _this._enableTexturesOffline = false;
  61133. _this.callbackManifestChecked(false);
  61134. };
  61135. var timeStampUsed = false;
  61136. var manifestURL = this.currentSceneUrl + ".manifest";
  61137. var xhr = new XMLHttpRequest();
  61138. if (navigator.onLine) {
  61139. // Adding a timestamp to by-pass browsers' cache
  61140. timeStampUsed = true;
  61141. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  61142. }
  61143. xhr.open("GET", manifestURL, true);
  61144. xhr.addEventListener("load", function () {
  61145. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  61146. try {
  61147. var manifestFile = JSON.parse(xhr.response);
  61148. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  61149. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  61150. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  61151. _this.manifestVersionFound = manifestFile.version;
  61152. }
  61153. if (_this.callbackManifestChecked) {
  61154. _this.callbackManifestChecked(true);
  61155. }
  61156. }
  61157. catch (ex) {
  61158. noManifestFile();
  61159. }
  61160. }
  61161. else {
  61162. noManifestFile();
  61163. }
  61164. }, false);
  61165. xhr.addEventListener("error", function (event) {
  61166. if (timeStampUsed) {
  61167. timeStampUsed = false;
  61168. // Let's retry without the timeStamp
  61169. // It could fail when coupled with HTML5 Offline API
  61170. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  61171. xhr.open("GET", retryManifestURL, true);
  61172. xhr.send();
  61173. }
  61174. else {
  61175. noManifestFile();
  61176. }
  61177. }, false);
  61178. try {
  61179. xhr.send();
  61180. }
  61181. catch (ex) {
  61182. BABYLON.Tools.Error("Error on XHR send request.");
  61183. this.callbackManifestChecked(false);
  61184. }
  61185. };
  61186. Database.prototype.openAsync = function (successCallback, errorCallback) {
  61187. var _this = this;
  61188. var handleError = function () {
  61189. _this.isSupported = false;
  61190. if (errorCallback)
  61191. errorCallback();
  61192. };
  61193. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  61194. // Your browser doesn't support IndexedDB
  61195. this.isSupported = false;
  61196. if (errorCallback)
  61197. errorCallback();
  61198. }
  61199. else {
  61200. // If the DB hasn't been opened or created yet
  61201. if (!this.db) {
  61202. this.hasReachedQuota = false;
  61203. this.isSupported = true;
  61204. var request = this.idbFactory.open("babylonjs", 1);
  61205. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  61206. request.onerror = function (event) {
  61207. handleError();
  61208. };
  61209. // executes when a version change transaction cannot complete due to other active transactions
  61210. request.onblocked = function (event) {
  61211. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  61212. handleError();
  61213. };
  61214. // DB has been opened successfully
  61215. request.onsuccess = function (event) {
  61216. _this.db = request.result;
  61217. successCallback();
  61218. };
  61219. // Initialization of the DB. Creating Scenes & Textures stores
  61220. request.onupgradeneeded = function (event) {
  61221. _this.db = (event.target).result;
  61222. if (_this.db) {
  61223. try {
  61224. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  61225. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  61226. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  61227. }
  61228. catch (ex) {
  61229. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  61230. handleError();
  61231. }
  61232. }
  61233. };
  61234. }
  61235. else {
  61236. if (successCallback)
  61237. successCallback();
  61238. }
  61239. }
  61240. };
  61241. Database.prototype.loadImageFromDB = function (url, image) {
  61242. var _this = this;
  61243. var completeURL = Database.ReturnFullUrlLocation(url);
  61244. var saveAndLoadImage = function () {
  61245. if (!_this.hasReachedQuota && _this.db !== null) {
  61246. // the texture is not yet in the DB, let's try to save it
  61247. _this._saveImageIntoDBAsync(completeURL, image);
  61248. }
  61249. else {
  61250. image.src = url;
  61251. }
  61252. };
  61253. if (!this.mustUpdateRessources) {
  61254. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  61255. }
  61256. else {
  61257. saveAndLoadImage();
  61258. }
  61259. };
  61260. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  61261. if (this.isSupported && this.db !== null) {
  61262. var texture;
  61263. var transaction = this.db.transaction(["textures"]);
  61264. transaction.onabort = function (event) {
  61265. image.src = url;
  61266. };
  61267. transaction.oncomplete = function (event) {
  61268. var blobTextureURL;
  61269. if (texture) {
  61270. var URL = window.URL || window.webkitURL;
  61271. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  61272. image.onerror = function () {
  61273. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  61274. image.src = url;
  61275. };
  61276. image.src = blobTextureURL;
  61277. }
  61278. else {
  61279. notInDBCallback();
  61280. }
  61281. };
  61282. var getRequest = transaction.objectStore("textures").get(url);
  61283. getRequest.onsuccess = function (event) {
  61284. texture = (event.target).result;
  61285. };
  61286. getRequest.onerror = function (event) {
  61287. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  61288. image.src = url;
  61289. };
  61290. }
  61291. else {
  61292. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61293. image.src = url;
  61294. }
  61295. };
  61296. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  61297. var _this = this;
  61298. if (this.isSupported) {
  61299. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  61300. var generateBlobUrl = function () {
  61301. var blobTextureURL;
  61302. if (blob) {
  61303. var URL = window.URL || window.webkitURL;
  61304. try {
  61305. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  61306. }
  61307. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  61308. catch (ex) {
  61309. blobTextureURL = URL.createObjectURL(blob);
  61310. }
  61311. }
  61312. if (blobTextureURL) {
  61313. image.src = blobTextureURL;
  61314. }
  61315. };
  61316. if (Database.IsUASupportingBlobStorage) {
  61317. var xhr = new XMLHttpRequest(), blob;
  61318. xhr.open("GET", url, true);
  61319. xhr.responseType = "blob";
  61320. xhr.addEventListener("load", function () {
  61321. if (xhr.status === 200 && _this.db) {
  61322. // Blob as response (XHR2)
  61323. blob = xhr.response;
  61324. var transaction = _this.db.transaction(["textures"], "readwrite");
  61325. // the transaction could abort because of a QuotaExceededError error
  61326. transaction.onabort = function (event) {
  61327. try {
  61328. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61329. var srcElement = (event.srcElement || event.target);
  61330. var error = srcElement.error;
  61331. if (error && error.name === "QuotaExceededError") {
  61332. _this.hasReachedQuota = true;
  61333. }
  61334. }
  61335. catch (ex) { }
  61336. generateBlobUrl();
  61337. };
  61338. transaction.oncomplete = function (event) {
  61339. generateBlobUrl();
  61340. };
  61341. var newTexture = { textureUrl: url, data: blob };
  61342. try {
  61343. // Put the blob into the dabase
  61344. var addRequest = transaction.objectStore("textures").put(newTexture);
  61345. addRequest.onsuccess = function (event) {
  61346. };
  61347. addRequest.onerror = function (event) {
  61348. generateBlobUrl();
  61349. };
  61350. }
  61351. catch (ex) {
  61352. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  61353. if (ex.code === 25) {
  61354. Database.IsUASupportingBlobStorage = false;
  61355. }
  61356. image.src = url;
  61357. }
  61358. }
  61359. else {
  61360. image.src = url;
  61361. }
  61362. }, false);
  61363. xhr.addEventListener("error", function (event) {
  61364. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  61365. image.src = url;
  61366. }, false);
  61367. xhr.send();
  61368. }
  61369. else {
  61370. image.src = url;
  61371. }
  61372. }
  61373. else {
  61374. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61375. image.src = url;
  61376. }
  61377. };
  61378. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  61379. var _this = this;
  61380. var updateVersion = function () {
  61381. // the version is not yet in the DB or we need to update it
  61382. _this._saveVersionIntoDBAsync(url, versionLoaded);
  61383. };
  61384. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  61385. };
  61386. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  61387. var _this = this;
  61388. if (this.isSupported && this.db) {
  61389. var version;
  61390. try {
  61391. var transaction = this.db.transaction(["versions"]);
  61392. transaction.oncomplete = function (event) {
  61393. if (version) {
  61394. // If the version in the JSON file is > than the version in DB
  61395. if (_this.manifestVersionFound > version.data) {
  61396. _this.mustUpdateRessources = true;
  61397. updateInDBCallback();
  61398. }
  61399. else {
  61400. callback(version.data);
  61401. }
  61402. }
  61403. else {
  61404. _this.mustUpdateRessources = true;
  61405. updateInDBCallback();
  61406. }
  61407. };
  61408. transaction.onabort = function (event) {
  61409. callback(-1);
  61410. };
  61411. var getRequest = transaction.objectStore("versions").get(url);
  61412. getRequest.onsuccess = function (event) {
  61413. version = (event.target).result;
  61414. };
  61415. getRequest.onerror = function (event) {
  61416. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  61417. callback(-1);
  61418. };
  61419. }
  61420. catch (ex) {
  61421. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  61422. callback(-1);
  61423. }
  61424. }
  61425. else {
  61426. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61427. callback(-1);
  61428. }
  61429. };
  61430. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  61431. var _this = this;
  61432. if (this.isSupported && !this.hasReachedQuota && this.db) {
  61433. try {
  61434. // Open a transaction to the database
  61435. var transaction = this.db.transaction(["versions"], "readwrite");
  61436. // the transaction could abort because of a QuotaExceededError error
  61437. transaction.onabort = function (event) {
  61438. try {
  61439. var error = event.srcElement['error'];
  61440. if (error && error.name === "QuotaExceededError") {
  61441. _this.hasReachedQuota = true;
  61442. }
  61443. }
  61444. catch (ex) { }
  61445. callback(-1);
  61446. };
  61447. transaction.oncomplete = function (event) {
  61448. callback(_this.manifestVersionFound);
  61449. };
  61450. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  61451. // Put the scene into the database
  61452. var addRequest = transaction.objectStore("versions").put(newVersion);
  61453. addRequest.onsuccess = function (event) {
  61454. };
  61455. addRequest.onerror = function (event) {
  61456. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  61457. };
  61458. }
  61459. catch (ex) {
  61460. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  61461. callback(-1);
  61462. }
  61463. }
  61464. else {
  61465. callback(-1);
  61466. }
  61467. };
  61468. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  61469. var _this = this;
  61470. var completeUrl = Database.ReturnFullUrlLocation(url);
  61471. var saveAndLoadFile = function () {
  61472. // the scene is not yet in the DB, let's try to save it
  61473. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  61474. };
  61475. this._checkVersionFromDB(completeUrl, function (version) {
  61476. if (version !== -1) {
  61477. if (!_this.mustUpdateRessources) {
  61478. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  61479. }
  61480. else {
  61481. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  61482. }
  61483. }
  61484. else {
  61485. if (errorCallback) {
  61486. errorCallback();
  61487. }
  61488. }
  61489. });
  61490. };
  61491. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  61492. if (this.isSupported && this.db) {
  61493. var targetStore;
  61494. if (url.indexOf(".babylon") !== -1) {
  61495. targetStore = "scenes";
  61496. }
  61497. else {
  61498. targetStore = "textures";
  61499. }
  61500. var file;
  61501. var transaction = this.db.transaction([targetStore]);
  61502. transaction.oncomplete = function (event) {
  61503. if (file) {
  61504. callback(file.data);
  61505. }
  61506. else {
  61507. notInDBCallback();
  61508. }
  61509. };
  61510. transaction.onabort = function (event) {
  61511. notInDBCallback();
  61512. };
  61513. var getRequest = transaction.objectStore(targetStore).get(url);
  61514. getRequest.onsuccess = function (event) {
  61515. file = (event.target).result;
  61516. };
  61517. getRequest.onerror = function (event) {
  61518. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  61519. notInDBCallback();
  61520. };
  61521. }
  61522. else {
  61523. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61524. callback();
  61525. }
  61526. };
  61527. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  61528. var _this = this;
  61529. if (this.isSupported) {
  61530. var targetStore;
  61531. if (url.indexOf(".babylon") !== -1) {
  61532. targetStore = "scenes";
  61533. }
  61534. else {
  61535. targetStore = "textures";
  61536. }
  61537. // Create XHR
  61538. var xhr = new XMLHttpRequest();
  61539. var fileData;
  61540. xhr.open("GET", url, true);
  61541. if (useArrayBuffer) {
  61542. xhr.responseType = "arraybuffer";
  61543. }
  61544. if (progressCallback) {
  61545. xhr.onprogress = progressCallback;
  61546. }
  61547. xhr.addEventListener("load", function () {
  61548. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  61549. // Blob as response (XHR2)
  61550. //fileData = xhr.responseText;
  61551. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  61552. if (!_this.hasReachedQuota && _this.db) {
  61553. // Open a transaction to the database
  61554. var transaction = _this.db.transaction([targetStore], "readwrite");
  61555. // the transaction could abort because of a QuotaExceededError error
  61556. transaction.onabort = function (event) {
  61557. try {
  61558. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61559. var error = event.srcElement['error'];
  61560. if (error && error.name === "QuotaExceededError") {
  61561. _this.hasReachedQuota = true;
  61562. }
  61563. }
  61564. catch (ex) { }
  61565. callback(fileData);
  61566. };
  61567. transaction.oncomplete = function (event) {
  61568. callback(fileData);
  61569. };
  61570. var newFile;
  61571. if (targetStore === "scenes") {
  61572. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  61573. }
  61574. else {
  61575. newFile = { textureUrl: url, data: fileData };
  61576. }
  61577. try {
  61578. // Put the scene into the database
  61579. var addRequest = transaction.objectStore(targetStore).put(newFile);
  61580. addRequest.onsuccess = function (event) {
  61581. };
  61582. addRequest.onerror = function (event) {
  61583. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  61584. };
  61585. }
  61586. catch (ex) {
  61587. callback(fileData);
  61588. }
  61589. }
  61590. else {
  61591. callback(fileData);
  61592. }
  61593. }
  61594. else {
  61595. callback();
  61596. }
  61597. }, false);
  61598. xhr.addEventListener("error", function (event) {
  61599. BABYLON.Tools.Error("error on XHR request.");
  61600. callback();
  61601. }, false);
  61602. xhr.send();
  61603. }
  61604. else {
  61605. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61606. callback();
  61607. }
  61608. };
  61609. Database.IsUASupportingBlobStorage = true;
  61610. Database.IDBStorageEnabled = true;
  61611. Database.parseURL = function (url) {
  61612. var a = document.createElement('a');
  61613. a.href = url;
  61614. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  61615. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  61616. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  61617. return absLocation;
  61618. };
  61619. Database.ReturnFullUrlLocation = function (url) {
  61620. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  61621. return (Database.parseURL(window.location.href) + url);
  61622. }
  61623. else {
  61624. return url;
  61625. }
  61626. };
  61627. return Database;
  61628. }());
  61629. BABYLON.Database = Database;
  61630. })(BABYLON || (BABYLON = {}));
  61631. //# sourceMappingURL=babylon.database.js.map
  61632. var BABYLON;
  61633. (function (BABYLON) {
  61634. var FresnelParameters = /** @class */ (function () {
  61635. function FresnelParameters() {
  61636. this._isEnabled = true;
  61637. this.leftColor = BABYLON.Color3.White();
  61638. this.rightColor = BABYLON.Color3.Black();
  61639. this.bias = 0;
  61640. this.power = 1;
  61641. }
  61642. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  61643. get: function () {
  61644. return this._isEnabled;
  61645. },
  61646. set: function (value) {
  61647. if (this._isEnabled === value) {
  61648. return;
  61649. }
  61650. this._isEnabled = value;
  61651. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  61652. },
  61653. enumerable: true,
  61654. configurable: true
  61655. });
  61656. FresnelParameters.prototype.clone = function () {
  61657. var newFresnelParameters = new FresnelParameters();
  61658. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  61659. return newFresnelParameters;
  61660. };
  61661. FresnelParameters.prototype.serialize = function () {
  61662. var serializationObject = {};
  61663. serializationObject.isEnabled = this.isEnabled;
  61664. serializationObject.leftColor = this.leftColor;
  61665. serializationObject.rightColor = this.rightColor;
  61666. serializationObject.bias = this.bias;
  61667. serializationObject.power = this.power;
  61668. return serializationObject;
  61669. };
  61670. FresnelParameters.Parse = function (parsedFresnelParameters) {
  61671. var fresnelParameters = new FresnelParameters();
  61672. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  61673. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  61674. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  61675. fresnelParameters.bias = parsedFresnelParameters.bias;
  61676. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  61677. return fresnelParameters;
  61678. };
  61679. return FresnelParameters;
  61680. }());
  61681. BABYLON.FresnelParameters = FresnelParameters;
  61682. })(BABYLON || (BABYLON = {}));
  61683. //# sourceMappingURL=babylon.fresnelParameters.js.map
  61684. var BABYLON;
  61685. (function (BABYLON) {
  61686. var MultiMaterial = /** @class */ (function (_super) {
  61687. __extends(MultiMaterial, _super);
  61688. function MultiMaterial(name, scene) {
  61689. var _this = _super.call(this, name, scene, true) || this;
  61690. scene.multiMaterials.push(_this);
  61691. _this.subMaterials = new Array();
  61692. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  61693. return _this;
  61694. }
  61695. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  61696. get: function () {
  61697. return this._subMaterials;
  61698. },
  61699. set: function (value) {
  61700. this._subMaterials = value;
  61701. this._hookArray(value);
  61702. },
  61703. enumerable: true,
  61704. configurable: true
  61705. });
  61706. MultiMaterial.prototype._hookArray = function (array) {
  61707. var _this = this;
  61708. var oldPush = array.push;
  61709. array.push = function () {
  61710. var items = [];
  61711. for (var _i = 0; _i < arguments.length; _i++) {
  61712. items[_i] = arguments[_i];
  61713. }
  61714. var result = oldPush.apply(array, items);
  61715. _this._markAllSubMeshesAsTexturesDirty();
  61716. return result;
  61717. };
  61718. var oldSplice = array.splice;
  61719. array.splice = function (index, deleteCount) {
  61720. var deleted = oldSplice.apply(array, [index, deleteCount]);
  61721. _this._markAllSubMeshesAsTexturesDirty();
  61722. return deleted;
  61723. };
  61724. };
  61725. // Properties
  61726. MultiMaterial.prototype.getSubMaterial = function (index) {
  61727. if (index < 0 || index >= this.subMaterials.length) {
  61728. return this.getScene().defaultMaterial;
  61729. }
  61730. return this.subMaterials[index];
  61731. };
  61732. MultiMaterial.prototype.getActiveTextures = function () {
  61733. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  61734. if (subMaterial) {
  61735. return subMaterial.getActiveTextures();
  61736. }
  61737. else {
  61738. return [];
  61739. }
  61740. }));
  61741. var _a;
  61742. };
  61743. // Methods
  61744. MultiMaterial.prototype.getClassName = function () {
  61745. return "MultiMaterial";
  61746. };
  61747. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  61748. for (var index = 0; index < this.subMaterials.length; index++) {
  61749. var subMaterial = this.subMaterials[index];
  61750. if (subMaterial) {
  61751. if (subMaterial.storeEffectOnSubMeshes) {
  61752. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  61753. return false;
  61754. }
  61755. continue;
  61756. }
  61757. if (!subMaterial.isReady(mesh)) {
  61758. return false;
  61759. }
  61760. }
  61761. }
  61762. return true;
  61763. };
  61764. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  61765. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  61766. for (var index = 0; index < this.subMaterials.length; index++) {
  61767. var subMaterial = null;
  61768. var current = this.subMaterials[index];
  61769. if (cloneChildren && current) {
  61770. subMaterial = current.clone(name + "-" + current.name);
  61771. }
  61772. else {
  61773. subMaterial = this.subMaterials[index];
  61774. }
  61775. newMultiMaterial.subMaterials.push(subMaterial);
  61776. }
  61777. return newMultiMaterial;
  61778. };
  61779. MultiMaterial.prototype.serialize = function () {
  61780. var serializationObject = {};
  61781. serializationObject.name = this.name;
  61782. serializationObject.id = this.id;
  61783. if (BABYLON.Tags) {
  61784. serializationObject.tags = BABYLON.Tags.GetTags(this);
  61785. }
  61786. serializationObject.materials = [];
  61787. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  61788. var subMat = this.subMaterials[matIndex];
  61789. if (subMat) {
  61790. serializationObject.materials.push(subMat.id);
  61791. }
  61792. else {
  61793. serializationObject.materials.push(null);
  61794. }
  61795. }
  61796. return serializationObject;
  61797. };
  61798. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61799. var scene = this.getScene();
  61800. if (!scene) {
  61801. return;
  61802. }
  61803. var index = scene.multiMaterials.indexOf(this);
  61804. if (index >= 0) {
  61805. scene.multiMaterials.splice(index, 1);
  61806. }
  61807. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61808. };
  61809. return MultiMaterial;
  61810. }(BABYLON.Material));
  61811. BABYLON.MultiMaterial = MultiMaterial;
  61812. })(BABYLON || (BABYLON = {}));
  61813. //# sourceMappingURL=babylon.multiMaterial.js.map
  61814. var BABYLON;
  61815. (function (BABYLON) {
  61816. var FreeCameraTouchInput = /** @class */ (function () {
  61817. function FreeCameraTouchInput() {
  61818. this._offsetX = null;
  61819. this._offsetY = null;
  61820. this._pointerPressed = new Array();
  61821. this.touchAngularSensibility = 200000.0;
  61822. this.touchMoveSensibility = 250.0;
  61823. }
  61824. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  61825. var _this = this;
  61826. var previousPosition = null;
  61827. if (this._pointerInput === undefined) {
  61828. this._onLostFocus = function (evt) {
  61829. _this._offsetX = null;
  61830. _this._offsetY = null;
  61831. };
  61832. this._pointerInput = function (p, s) {
  61833. var evt = p.event;
  61834. if (evt.pointerType === "mouse") {
  61835. return;
  61836. }
  61837. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  61838. if (!noPreventDefault) {
  61839. evt.preventDefault();
  61840. }
  61841. _this._pointerPressed.push(evt.pointerId);
  61842. if (_this._pointerPressed.length !== 1) {
  61843. return;
  61844. }
  61845. previousPosition = {
  61846. x: evt.clientX,
  61847. y: evt.clientY
  61848. };
  61849. }
  61850. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  61851. if (!noPreventDefault) {
  61852. evt.preventDefault();
  61853. }
  61854. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61855. if (index === -1) {
  61856. return;
  61857. }
  61858. _this._pointerPressed.splice(index, 1);
  61859. if (index != 0) {
  61860. return;
  61861. }
  61862. previousPosition = null;
  61863. _this._offsetX = null;
  61864. _this._offsetY = null;
  61865. }
  61866. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  61867. if (!noPreventDefault) {
  61868. evt.preventDefault();
  61869. }
  61870. if (!previousPosition) {
  61871. return;
  61872. }
  61873. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61874. if (index != 0) {
  61875. return;
  61876. }
  61877. _this._offsetX = evt.clientX - previousPosition.x;
  61878. _this._offsetY = -(evt.clientY - previousPosition.y);
  61879. }
  61880. };
  61881. }
  61882. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  61883. if (this._onLostFocus) {
  61884. element.addEventListener("blur", this._onLostFocus);
  61885. }
  61886. };
  61887. FreeCameraTouchInput.prototype.detachControl = function (element) {
  61888. if (this._pointerInput && element) {
  61889. if (this._observer) {
  61890. this.camera.getScene().onPointerObservable.remove(this._observer);
  61891. this._observer = null;
  61892. }
  61893. if (this._onLostFocus) {
  61894. element.removeEventListener("blur", this._onLostFocus);
  61895. this._onLostFocus = null;
  61896. }
  61897. this._pointerPressed = [];
  61898. this._offsetX = null;
  61899. this._offsetY = null;
  61900. }
  61901. };
  61902. FreeCameraTouchInput.prototype.checkInputs = function () {
  61903. if (this._offsetX && this._offsetY) {
  61904. var camera = this.camera;
  61905. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  61906. if (this._pointerPressed.length > 1) {
  61907. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  61908. }
  61909. else {
  61910. var speed = camera._computeLocalCameraSpeed();
  61911. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  61912. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  61913. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  61914. }
  61915. }
  61916. };
  61917. FreeCameraTouchInput.prototype.getClassName = function () {
  61918. return "FreeCameraTouchInput";
  61919. };
  61920. FreeCameraTouchInput.prototype.getSimpleName = function () {
  61921. return "touch";
  61922. };
  61923. __decorate([
  61924. BABYLON.serialize()
  61925. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  61926. __decorate([
  61927. BABYLON.serialize()
  61928. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  61929. return FreeCameraTouchInput;
  61930. }());
  61931. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  61932. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  61933. })(BABYLON || (BABYLON = {}));
  61934. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  61935. var BABYLON;
  61936. (function (BABYLON) {
  61937. // We're mainly based on the logic defined into the FreeCamera code
  61938. var TouchCamera = /** @class */ (function (_super) {
  61939. __extends(TouchCamera, _super);
  61940. //-- end properties for backward compatibility for inputs
  61941. function TouchCamera(name, position, scene) {
  61942. var _this = _super.call(this, name, position, scene) || this;
  61943. _this.inputs.addTouch();
  61944. _this._setupInputs();
  61945. return _this;
  61946. }
  61947. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  61948. //-- Begin properties for backward compatibility for inputs
  61949. get: function () {
  61950. var touch = this.inputs.attached["touch"];
  61951. if (touch)
  61952. return touch.touchAngularSensibility;
  61953. return 0;
  61954. },
  61955. set: function (value) {
  61956. var touch = this.inputs.attached["touch"];
  61957. if (touch)
  61958. touch.touchAngularSensibility = value;
  61959. },
  61960. enumerable: true,
  61961. configurable: true
  61962. });
  61963. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  61964. get: function () {
  61965. var touch = this.inputs.attached["touch"];
  61966. if (touch)
  61967. return touch.touchMoveSensibility;
  61968. return 0;
  61969. },
  61970. set: function (value) {
  61971. var touch = this.inputs.attached["touch"];
  61972. if (touch)
  61973. touch.touchMoveSensibility = value;
  61974. },
  61975. enumerable: true,
  61976. configurable: true
  61977. });
  61978. TouchCamera.prototype.getClassName = function () {
  61979. return "TouchCamera";
  61980. };
  61981. TouchCamera.prototype._setupInputs = function () {
  61982. var mouse = this.inputs.attached["mouse"];
  61983. if (mouse) {
  61984. mouse.touchEnabled = false;
  61985. }
  61986. };
  61987. return TouchCamera;
  61988. }(BABYLON.FreeCamera));
  61989. BABYLON.TouchCamera = TouchCamera;
  61990. })(BABYLON || (BABYLON = {}));
  61991. //# sourceMappingURL=babylon.touchCamera.js.map
  61992. var BABYLON;
  61993. (function (BABYLON) {
  61994. var ProceduralTexture = /** @class */ (function (_super) {
  61995. __extends(ProceduralTexture, _super);
  61996. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  61997. if (fallbackTexture === void 0) { fallbackTexture = null; }
  61998. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61999. if (isCube === void 0) { isCube = false; }
  62000. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62001. _this.isCube = isCube;
  62002. _this.isEnabled = true;
  62003. _this._currentRefreshId = -1;
  62004. _this._refreshRate = 1;
  62005. _this._vertexBuffers = {};
  62006. _this._uniforms = new Array();
  62007. _this._samplers = new Array();
  62008. _this._textures = {};
  62009. _this._floats = {};
  62010. _this._floatsArrays = {};
  62011. _this._colors3 = {};
  62012. _this._colors4 = {};
  62013. _this._vectors2 = {};
  62014. _this._vectors3 = {};
  62015. _this._matrices = {};
  62016. _this._fallbackTextureUsed = false;
  62017. scene._proceduralTextures.push(_this);
  62018. _this._engine = scene.getEngine();
  62019. _this.name = name;
  62020. _this.isRenderTarget = true;
  62021. _this._size = size;
  62022. _this._generateMipMaps = generateMipMaps;
  62023. _this.setFragment(fragment);
  62024. _this._fallbackTexture = fallbackTexture;
  62025. if (isCube) {
  62026. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  62027. _this.setFloat("face", 0);
  62028. }
  62029. else {
  62030. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  62031. }
  62032. // VBO
  62033. var vertices = [];
  62034. vertices.push(1, 1);
  62035. vertices.push(-1, 1);
  62036. vertices.push(-1, -1);
  62037. vertices.push(1, -1);
  62038. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  62039. _this._createIndexBuffer();
  62040. return _this;
  62041. }
  62042. ProceduralTexture.prototype._createIndexBuffer = function () {
  62043. var engine = this._engine;
  62044. // Indices
  62045. var indices = [];
  62046. indices.push(0);
  62047. indices.push(1);
  62048. indices.push(2);
  62049. indices.push(0);
  62050. indices.push(2);
  62051. indices.push(3);
  62052. this._indexBuffer = engine.createIndexBuffer(indices);
  62053. };
  62054. ProceduralTexture.prototype._rebuild = function () {
  62055. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62056. if (vb) {
  62057. vb._rebuild();
  62058. }
  62059. this._createIndexBuffer();
  62060. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  62061. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  62062. }
  62063. };
  62064. ProceduralTexture.prototype.reset = function () {
  62065. if (this._effect === undefined) {
  62066. return;
  62067. }
  62068. var engine = this._engine;
  62069. engine._releaseEffect(this._effect);
  62070. };
  62071. ProceduralTexture.prototype.isReady = function () {
  62072. var _this = this;
  62073. var engine = this._engine;
  62074. var shaders;
  62075. if (!this._fragment) {
  62076. return false;
  62077. }
  62078. if (this._fallbackTextureUsed) {
  62079. return true;
  62080. }
  62081. if (this._fragment.fragmentElement !== undefined) {
  62082. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  62083. }
  62084. else {
  62085. shaders = { vertex: "procedural", fragment: this._fragment };
  62086. }
  62087. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  62088. _this.releaseInternalTexture();
  62089. if (_this._fallbackTexture) {
  62090. _this._texture = _this._fallbackTexture._texture;
  62091. if (_this._texture) {
  62092. _this._texture.incrementReferences();
  62093. }
  62094. }
  62095. _this._fallbackTextureUsed = true;
  62096. });
  62097. return this._effect.isReady();
  62098. };
  62099. ProceduralTexture.prototype.resetRefreshCounter = function () {
  62100. this._currentRefreshId = -1;
  62101. };
  62102. ProceduralTexture.prototype.setFragment = function (fragment) {
  62103. this._fragment = fragment;
  62104. };
  62105. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  62106. get: function () {
  62107. return this._refreshRate;
  62108. },
  62109. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62110. set: function (value) {
  62111. this._refreshRate = value;
  62112. this.resetRefreshCounter();
  62113. },
  62114. enumerable: true,
  62115. configurable: true
  62116. });
  62117. ProceduralTexture.prototype._shouldRender = function () {
  62118. if (!this.isEnabled || !this.isReady() || !this._texture) {
  62119. return false;
  62120. }
  62121. if (this._fallbackTextureUsed) {
  62122. return false;
  62123. }
  62124. if (this._currentRefreshId === -1) {
  62125. this._currentRefreshId = 1;
  62126. return true;
  62127. }
  62128. if (this.refreshRate === this._currentRefreshId) {
  62129. this._currentRefreshId = 1;
  62130. return true;
  62131. }
  62132. this._currentRefreshId++;
  62133. return false;
  62134. };
  62135. ProceduralTexture.prototype.getRenderSize = function () {
  62136. return this._size;
  62137. };
  62138. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  62139. if (this._fallbackTextureUsed) {
  62140. return;
  62141. }
  62142. this.releaseInternalTexture();
  62143. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  62144. };
  62145. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  62146. if (this._uniforms.indexOf(uniformName) === -1) {
  62147. this._uniforms.push(uniformName);
  62148. }
  62149. };
  62150. ProceduralTexture.prototype.setTexture = function (name, texture) {
  62151. if (this._samplers.indexOf(name) === -1) {
  62152. this._samplers.push(name);
  62153. }
  62154. this._textures[name] = texture;
  62155. return this;
  62156. };
  62157. ProceduralTexture.prototype.setFloat = function (name, value) {
  62158. this._checkUniform(name);
  62159. this._floats[name] = value;
  62160. return this;
  62161. };
  62162. ProceduralTexture.prototype.setFloats = function (name, value) {
  62163. this._checkUniform(name);
  62164. this._floatsArrays[name] = value;
  62165. return this;
  62166. };
  62167. ProceduralTexture.prototype.setColor3 = function (name, value) {
  62168. this._checkUniform(name);
  62169. this._colors3[name] = value;
  62170. return this;
  62171. };
  62172. ProceduralTexture.prototype.setColor4 = function (name, value) {
  62173. this._checkUniform(name);
  62174. this._colors4[name] = value;
  62175. return this;
  62176. };
  62177. ProceduralTexture.prototype.setVector2 = function (name, value) {
  62178. this._checkUniform(name);
  62179. this._vectors2[name] = value;
  62180. return this;
  62181. };
  62182. ProceduralTexture.prototype.setVector3 = function (name, value) {
  62183. this._checkUniform(name);
  62184. this._vectors3[name] = value;
  62185. return this;
  62186. };
  62187. ProceduralTexture.prototype.setMatrix = function (name, value) {
  62188. this._checkUniform(name);
  62189. this._matrices[name] = value;
  62190. return this;
  62191. };
  62192. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62193. var scene = this.getScene();
  62194. if (!scene) {
  62195. return;
  62196. }
  62197. var engine = this._engine;
  62198. // Render
  62199. engine.enableEffect(this._effect);
  62200. engine.setState(false);
  62201. // Texture
  62202. for (var name in this._textures) {
  62203. this._effect.setTexture(name, this._textures[name]);
  62204. }
  62205. // Float
  62206. for (name in this._floats) {
  62207. this._effect.setFloat(name, this._floats[name]);
  62208. }
  62209. // Floats
  62210. for (name in this._floatsArrays) {
  62211. this._effect.setArray(name, this._floatsArrays[name]);
  62212. }
  62213. // Color3
  62214. for (name in this._colors3) {
  62215. this._effect.setColor3(name, this._colors3[name]);
  62216. }
  62217. // Color4
  62218. for (name in this._colors4) {
  62219. var color = this._colors4[name];
  62220. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62221. }
  62222. // Vector2
  62223. for (name in this._vectors2) {
  62224. this._effect.setVector2(name, this._vectors2[name]);
  62225. }
  62226. // Vector3
  62227. for (name in this._vectors3) {
  62228. this._effect.setVector3(name, this._vectors3[name]);
  62229. }
  62230. // Matrix
  62231. for (name in this._matrices) {
  62232. this._effect.setMatrix(name, this._matrices[name]);
  62233. }
  62234. if (!this._texture) {
  62235. return;
  62236. }
  62237. if (this.isCube) {
  62238. for (var face = 0; face < 6; face++) {
  62239. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  62240. // VBOs
  62241. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62242. this._effect.setFloat("face", face);
  62243. // Clear
  62244. engine.clear(scene.clearColor, true, true, true);
  62245. // Draw order
  62246. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62247. // Mipmaps
  62248. if (face === 5) {
  62249. engine.generateMipMapsForCubemap(this._texture);
  62250. }
  62251. }
  62252. }
  62253. else {
  62254. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  62255. // VBOs
  62256. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62257. // Clear
  62258. engine.clear(scene.clearColor, true, true, true);
  62259. // Draw order
  62260. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62261. }
  62262. // Unbind
  62263. engine.unBindFramebuffer(this._texture, this.isCube);
  62264. if (this.onGenerated) {
  62265. this.onGenerated();
  62266. }
  62267. };
  62268. ProceduralTexture.prototype.clone = function () {
  62269. var textureSize = this.getSize();
  62270. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  62271. // Base texture
  62272. newTexture.hasAlpha = this.hasAlpha;
  62273. newTexture.level = this.level;
  62274. // RenderTarget Texture
  62275. newTexture.coordinatesMode = this.coordinatesMode;
  62276. return newTexture;
  62277. };
  62278. ProceduralTexture.prototype.dispose = function () {
  62279. var scene = this.getScene();
  62280. if (!scene) {
  62281. return;
  62282. }
  62283. var index = scene._proceduralTextures.indexOf(this);
  62284. if (index >= 0) {
  62285. scene._proceduralTextures.splice(index, 1);
  62286. }
  62287. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62288. if (vertexBuffer) {
  62289. vertexBuffer.dispose();
  62290. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62291. }
  62292. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  62293. this._indexBuffer = null;
  62294. }
  62295. _super.prototype.dispose.call(this);
  62296. };
  62297. return ProceduralTexture;
  62298. }(BABYLON.Texture));
  62299. BABYLON.ProceduralTexture = ProceduralTexture;
  62300. })(BABYLON || (BABYLON = {}));
  62301. //# sourceMappingURL=babylon.proceduralTexture.js.map
  62302. var BABYLON;
  62303. (function (BABYLON) {
  62304. var CustomProceduralTexture = /** @class */ (function (_super) {
  62305. __extends(CustomProceduralTexture, _super);
  62306. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  62307. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  62308. _this._animate = true;
  62309. _this._time = 0;
  62310. _this._texturePath = texturePath;
  62311. //Try to load json
  62312. _this.loadJson(texturePath);
  62313. _this.refreshRate = 1;
  62314. return _this;
  62315. }
  62316. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  62317. var _this = this;
  62318. var noConfigFile = function () {
  62319. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  62320. try {
  62321. _this.setFragment(_this._texturePath);
  62322. }
  62323. catch (ex) {
  62324. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  62325. }
  62326. };
  62327. var configFileUrl = jsonUrl + "/config.json";
  62328. var xhr = new XMLHttpRequest();
  62329. xhr.open("GET", configFileUrl, true);
  62330. xhr.addEventListener("load", function () {
  62331. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62332. try {
  62333. _this._config = JSON.parse(xhr.response);
  62334. _this.updateShaderUniforms();
  62335. _this.updateTextures();
  62336. _this.setFragment(_this._texturePath + "/custom");
  62337. _this._animate = _this._config.animate;
  62338. _this.refreshRate = _this._config.refreshrate;
  62339. }
  62340. catch (ex) {
  62341. noConfigFile();
  62342. }
  62343. }
  62344. else {
  62345. noConfigFile();
  62346. }
  62347. }, false);
  62348. xhr.addEventListener("error", function () {
  62349. noConfigFile();
  62350. }, false);
  62351. try {
  62352. xhr.send();
  62353. }
  62354. catch (ex) {
  62355. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  62356. }
  62357. };
  62358. CustomProceduralTexture.prototype.isReady = function () {
  62359. if (!_super.prototype.isReady.call(this)) {
  62360. return false;
  62361. }
  62362. for (var name in this._textures) {
  62363. var texture = this._textures[name];
  62364. if (!texture.isReady()) {
  62365. return false;
  62366. }
  62367. }
  62368. return true;
  62369. };
  62370. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62371. var scene = this.getScene();
  62372. if (this._animate && scene) {
  62373. this._time += scene.getAnimationRatio() * 0.03;
  62374. this.updateShaderUniforms();
  62375. }
  62376. _super.prototype.render.call(this, useCameraPostProcess);
  62377. };
  62378. CustomProceduralTexture.prototype.updateTextures = function () {
  62379. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  62380. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  62381. }
  62382. };
  62383. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  62384. if (this._config) {
  62385. for (var j = 0; j < this._config.uniforms.length; j++) {
  62386. var uniform = this._config.uniforms[j];
  62387. switch (uniform.type) {
  62388. case "float":
  62389. this.setFloat(uniform.name, uniform.value);
  62390. break;
  62391. case "color3":
  62392. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  62393. break;
  62394. case "color4":
  62395. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  62396. break;
  62397. case "vector2":
  62398. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  62399. break;
  62400. case "vector3":
  62401. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  62402. break;
  62403. }
  62404. }
  62405. }
  62406. this.setFloat("time", this._time);
  62407. };
  62408. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  62409. get: function () {
  62410. return this._animate;
  62411. },
  62412. set: function (value) {
  62413. this._animate = value;
  62414. },
  62415. enumerable: true,
  62416. configurable: true
  62417. });
  62418. return CustomProceduralTexture;
  62419. }(BABYLON.ProceduralTexture));
  62420. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  62421. })(BABYLON || (BABYLON = {}));
  62422. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  62423. var BABYLON;
  62424. (function (BABYLON) {
  62425. var FreeCameraGamepadInput = /** @class */ (function () {
  62426. function FreeCameraGamepadInput() {
  62427. this.gamepadAngularSensibility = 200;
  62428. this.gamepadMoveSensibility = 40;
  62429. // private members
  62430. this._cameraTransform = BABYLON.Matrix.Identity();
  62431. this._deltaTransform = BABYLON.Vector3.Zero();
  62432. this._vector3 = BABYLON.Vector3.Zero();
  62433. this._vector2 = BABYLON.Vector2.Zero();
  62434. }
  62435. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62436. var _this = this;
  62437. var manager = this.camera.getScene().gamepadManager;
  62438. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62439. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62440. // prioritize XBOX gamepads.
  62441. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62442. _this.gamepad = gamepad;
  62443. }
  62444. }
  62445. });
  62446. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62447. if (_this.gamepad === gamepad) {
  62448. _this.gamepad = null;
  62449. }
  62450. });
  62451. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62452. };
  62453. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  62454. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62455. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62456. this.gamepad = null;
  62457. };
  62458. FreeCameraGamepadInput.prototype.checkInputs = function () {
  62459. if (this.gamepad && this.gamepad.leftStick) {
  62460. var camera = this.camera;
  62461. var LSValues = this.gamepad.leftStick;
  62462. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  62463. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62464. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  62465. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  62466. var RSValues = this.gamepad.rightStick;
  62467. if (RSValues) {
  62468. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  62469. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  62470. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  62471. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  62472. }
  62473. else {
  62474. RSValues = { x: 0, y: 0 };
  62475. }
  62476. if (!camera.rotationQuaternion) {
  62477. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  62478. }
  62479. else {
  62480. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  62481. }
  62482. var speed = camera._computeLocalCameraSpeed() * 50.0;
  62483. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  62484. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  62485. camera.cameraDirection.addInPlace(this._deltaTransform);
  62486. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  62487. camera.cameraRotation.addInPlace(this._vector2);
  62488. }
  62489. };
  62490. FreeCameraGamepadInput.prototype.getClassName = function () {
  62491. return "FreeCameraGamepadInput";
  62492. };
  62493. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  62494. return "gamepad";
  62495. };
  62496. __decorate([
  62497. BABYLON.serialize()
  62498. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  62499. __decorate([
  62500. BABYLON.serialize()
  62501. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62502. return FreeCameraGamepadInput;
  62503. }());
  62504. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  62505. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  62506. })(BABYLON || (BABYLON = {}));
  62507. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  62508. var BABYLON;
  62509. (function (BABYLON) {
  62510. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  62511. function ArcRotateCameraGamepadInput() {
  62512. this.gamepadRotationSensibility = 80;
  62513. this.gamepadMoveSensibility = 40;
  62514. }
  62515. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62516. var _this = this;
  62517. var manager = this.camera.getScene().gamepadManager;
  62518. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62519. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62520. // prioritize XBOX gamepads.
  62521. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62522. _this.gamepad = gamepad;
  62523. }
  62524. }
  62525. });
  62526. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62527. if (_this.gamepad === gamepad) {
  62528. _this.gamepad = null;
  62529. }
  62530. });
  62531. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62532. };
  62533. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  62534. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62535. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62536. this.gamepad = null;
  62537. };
  62538. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  62539. if (this.gamepad) {
  62540. var camera = this.camera;
  62541. var RSValues = this.gamepad.rightStick;
  62542. if (RSValues) {
  62543. if (RSValues.x != 0) {
  62544. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  62545. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  62546. camera.inertialAlphaOffset += normalizedRX;
  62547. }
  62548. }
  62549. if (RSValues.y != 0) {
  62550. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  62551. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  62552. camera.inertialBetaOffset += normalizedRY;
  62553. }
  62554. }
  62555. }
  62556. var LSValues = this.gamepad.leftStick;
  62557. if (LSValues && LSValues.y != 0) {
  62558. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62559. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  62560. this.camera.inertialRadiusOffset -= normalizedLY;
  62561. }
  62562. }
  62563. }
  62564. };
  62565. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  62566. return "ArcRotateCameraGamepadInput";
  62567. };
  62568. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  62569. return "gamepad";
  62570. };
  62571. __decorate([
  62572. BABYLON.serialize()
  62573. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  62574. __decorate([
  62575. BABYLON.serialize()
  62576. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62577. return ArcRotateCameraGamepadInput;
  62578. }());
  62579. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  62580. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  62581. })(BABYLON || (BABYLON = {}));
  62582. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  62583. var BABYLON;
  62584. (function (BABYLON) {
  62585. var GamepadManager = /** @class */ (function () {
  62586. function GamepadManager(_scene) {
  62587. var _this = this;
  62588. this._scene = _scene;
  62589. this._babylonGamepads = [];
  62590. this._oneGamepadConnected = false;
  62591. this._isMonitoring = false;
  62592. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  62593. if (!BABYLON.Tools.IsWindowObjectExist()) {
  62594. this._gamepadEventSupported = false;
  62595. }
  62596. else {
  62597. this._gamepadEventSupported = 'GamepadEvent' in window;
  62598. this._gamepadSupport = (navigator.getGamepads ||
  62599. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  62600. }
  62601. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  62602. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  62603. for (var i in _this._babylonGamepads) {
  62604. var gamepad = _this._babylonGamepads[i];
  62605. if (gamepad && gamepad._isConnected) {
  62606. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  62607. }
  62608. }
  62609. });
  62610. this._onGamepadConnectedEvent = function (evt) {
  62611. var gamepad = evt.gamepad;
  62612. if (gamepad.index in _this._babylonGamepads) {
  62613. if (_this._babylonGamepads[gamepad.index].isConnected) {
  62614. return;
  62615. }
  62616. }
  62617. var newGamepad;
  62618. if (_this._babylonGamepads[gamepad.index]) {
  62619. newGamepad = _this._babylonGamepads[gamepad.index];
  62620. newGamepad.browserGamepad = gamepad;
  62621. newGamepad._isConnected = true;
  62622. }
  62623. else {
  62624. newGamepad = _this._addNewGamepad(gamepad);
  62625. }
  62626. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62627. _this._startMonitoringGamepads();
  62628. };
  62629. this._onGamepadDisconnectedEvent = function (evt) {
  62630. var gamepad = evt.gamepad;
  62631. // Remove the gamepad from the list of gamepads to monitor.
  62632. for (var i in _this._babylonGamepads) {
  62633. if (_this._babylonGamepads[i].index === gamepad.index) {
  62634. var disconnectedGamepad = _this._babylonGamepads[i];
  62635. disconnectedGamepad._isConnected = false;
  62636. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  62637. break;
  62638. }
  62639. }
  62640. };
  62641. if (this._gamepadSupport) {
  62642. //first add already-connected gamepads
  62643. this._updateGamepadObjects();
  62644. if (this._babylonGamepads.length) {
  62645. this._startMonitoringGamepads();
  62646. }
  62647. // Checking if the gamepad connected event is supported (like in Firefox)
  62648. if (this._gamepadEventSupported) {
  62649. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  62650. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  62651. }
  62652. else {
  62653. this._startMonitoringGamepads();
  62654. }
  62655. }
  62656. }
  62657. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  62658. get: function () {
  62659. return this._babylonGamepads;
  62660. },
  62661. enumerable: true,
  62662. configurable: true
  62663. });
  62664. GamepadManager.prototype.getGamepadByType = function (type) {
  62665. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  62666. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  62667. var gamepad = _a[_i];
  62668. if (gamepad && gamepad.type === type) {
  62669. return gamepad;
  62670. }
  62671. }
  62672. return null;
  62673. };
  62674. GamepadManager.prototype.dispose = function () {
  62675. if (this._gamepadEventSupported) {
  62676. if (this._onGamepadConnectedEvent) {
  62677. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  62678. }
  62679. if (this._onGamepadDisconnectedEvent) {
  62680. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  62681. }
  62682. this._onGamepadConnectedEvent = null;
  62683. this._onGamepadDisconnectedEvent = null;
  62684. }
  62685. this._babylonGamepads.forEach(function (gamepad) {
  62686. gamepad.dispose();
  62687. });
  62688. this.onGamepadConnectedObservable.clear();
  62689. this.onGamepadDisconnectedObservable.clear();
  62690. this._oneGamepadConnected = false;
  62691. this._stopMonitoringGamepads();
  62692. this._babylonGamepads = [];
  62693. };
  62694. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  62695. if (!this._oneGamepadConnected) {
  62696. this._oneGamepadConnected = true;
  62697. }
  62698. var newGamepad;
  62699. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  62700. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  62701. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  62702. }
  62703. else if (gamepad.pose) {
  62704. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  62705. }
  62706. else {
  62707. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  62708. }
  62709. this._babylonGamepads[newGamepad.index] = newGamepad;
  62710. return newGamepad;
  62711. };
  62712. GamepadManager.prototype._startMonitoringGamepads = function () {
  62713. if (!this._isMonitoring) {
  62714. this._isMonitoring = true;
  62715. //back-comp
  62716. if (!this._scene) {
  62717. this._checkGamepadsStatus();
  62718. }
  62719. }
  62720. };
  62721. GamepadManager.prototype._stopMonitoringGamepads = function () {
  62722. this._isMonitoring = false;
  62723. };
  62724. GamepadManager.prototype._checkGamepadsStatus = function () {
  62725. var _this = this;
  62726. // Hack to be compatible Chrome
  62727. this._updateGamepadObjects();
  62728. for (var i in this._babylonGamepads) {
  62729. var gamepad = this._babylonGamepads[i];
  62730. if (!gamepad || !gamepad.isConnected) {
  62731. continue;
  62732. }
  62733. gamepad.update();
  62734. }
  62735. if (this._isMonitoring && !this._scene) {
  62736. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  62737. }
  62738. };
  62739. // This function is called only on Chrome, which does not properly support
  62740. // connection/disconnection events and forces you to recopy again the gamepad object
  62741. GamepadManager.prototype._updateGamepadObjects = function () {
  62742. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  62743. for (var i = 0; i < gamepads.length; i++) {
  62744. if (gamepads[i]) {
  62745. if (!this._babylonGamepads[gamepads[i].index]) {
  62746. var newGamepad = this._addNewGamepad(gamepads[i]);
  62747. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62748. }
  62749. else {
  62750. // Forced to copy again this object for Chrome for unknown reason
  62751. this._babylonGamepads[i].browserGamepad = gamepads[i];
  62752. if (!this._babylonGamepads[i].isConnected) {
  62753. this._babylonGamepads[i]._isConnected = true;
  62754. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  62755. }
  62756. }
  62757. }
  62758. }
  62759. };
  62760. return GamepadManager;
  62761. }());
  62762. BABYLON.GamepadManager = GamepadManager;
  62763. })(BABYLON || (BABYLON = {}));
  62764. //# sourceMappingURL=babylon.gamepadManager.js.map
  62765. var BABYLON;
  62766. (function (BABYLON) {
  62767. var StickValues = /** @class */ (function () {
  62768. function StickValues(x, y) {
  62769. this.x = x;
  62770. this.y = y;
  62771. }
  62772. return StickValues;
  62773. }());
  62774. BABYLON.StickValues = StickValues;
  62775. var Gamepad = /** @class */ (function () {
  62776. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  62777. if (leftStickX === void 0) { leftStickX = 0; }
  62778. if (leftStickY === void 0) { leftStickY = 1; }
  62779. if (rightStickX === void 0) { rightStickX = 2; }
  62780. if (rightStickY === void 0) { rightStickY = 3; }
  62781. this.id = id;
  62782. this.index = index;
  62783. this.browserGamepad = browserGamepad;
  62784. this._isConnected = true;
  62785. this._invertLeftStickY = false;
  62786. this.type = Gamepad.GAMEPAD;
  62787. this._leftStickAxisX = leftStickX;
  62788. this._leftStickAxisY = leftStickY;
  62789. this._rightStickAxisX = rightStickX;
  62790. this._rightStickAxisY = rightStickY;
  62791. if (this.browserGamepad.axes.length >= 2) {
  62792. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62793. }
  62794. if (this.browserGamepad.axes.length >= 4) {
  62795. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62796. }
  62797. }
  62798. Object.defineProperty(Gamepad.prototype, "isConnected", {
  62799. get: function () {
  62800. return this._isConnected;
  62801. },
  62802. enumerable: true,
  62803. configurable: true
  62804. });
  62805. Gamepad.prototype.onleftstickchanged = function (callback) {
  62806. this._onleftstickchanged = callback;
  62807. };
  62808. Gamepad.prototype.onrightstickchanged = function (callback) {
  62809. this._onrightstickchanged = callback;
  62810. };
  62811. Object.defineProperty(Gamepad.prototype, "leftStick", {
  62812. get: function () {
  62813. return this._leftStick;
  62814. },
  62815. set: function (newValues) {
  62816. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  62817. this._onleftstickchanged(newValues);
  62818. }
  62819. this._leftStick = newValues;
  62820. },
  62821. enumerable: true,
  62822. configurable: true
  62823. });
  62824. Object.defineProperty(Gamepad.prototype, "rightStick", {
  62825. get: function () {
  62826. return this._rightStick;
  62827. },
  62828. set: function (newValues) {
  62829. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  62830. this._onrightstickchanged(newValues);
  62831. }
  62832. this._rightStick = newValues;
  62833. },
  62834. enumerable: true,
  62835. configurable: true
  62836. });
  62837. Gamepad.prototype.update = function () {
  62838. if (this._leftStick) {
  62839. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62840. if (this._invertLeftStickY) {
  62841. this.leftStick.y *= -1;
  62842. }
  62843. }
  62844. if (this._rightStick) {
  62845. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62846. }
  62847. };
  62848. Gamepad.prototype.dispose = function () {
  62849. };
  62850. Gamepad.GAMEPAD = 0;
  62851. Gamepad.GENERIC = 1;
  62852. Gamepad.XBOX = 2;
  62853. Gamepad.POSE_ENABLED = 3;
  62854. return Gamepad;
  62855. }());
  62856. BABYLON.Gamepad = Gamepad;
  62857. var GenericPad = /** @class */ (function (_super) {
  62858. __extends(GenericPad, _super);
  62859. function GenericPad(id, index, browserGamepad) {
  62860. var _this = _super.call(this, id, index, browserGamepad) || this;
  62861. _this.onButtonDownObservable = new BABYLON.Observable();
  62862. _this.onButtonUpObservable = new BABYLON.Observable();
  62863. _this.type = Gamepad.GENERIC;
  62864. _this._buttons = new Array(browserGamepad.buttons.length);
  62865. return _this;
  62866. }
  62867. GenericPad.prototype.onbuttondown = function (callback) {
  62868. this._onbuttondown = callback;
  62869. };
  62870. GenericPad.prototype.onbuttonup = function (callback) {
  62871. this._onbuttonup = callback;
  62872. };
  62873. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  62874. if (newValue !== currentValue) {
  62875. if (newValue === 1) {
  62876. if (this._onbuttondown) {
  62877. this._onbuttondown(buttonIndex);
  62878. }
  62879. this.onButtonDownObservable.notifyObservers(buttonIndex);
  62880. }
  62881. if (newValue === 0) {
  62882. if (this._onbuttonup) {
  62883. this._onbuttonup(buttonIndex);
  62884. }
  62885. this.onButtonUpObservable.notifyObservers(buttonIndex);
  62886. }
  62887. }
  62888. return newValue;
  62889. };
  62890. GenericPad.prototype.update = function () {
  62891. _super.prototype.update.call(this);
  62892. for (var index = 0; index < this._buttons.length; index++) {
  62893. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  62894. }
  62895. };
  62896. GenericPad.prototype.dispose = function () {
  62897. _super.prototype.dispose.call(this);
  62898. this.onButtonDownObservable.clear();
  62899. this.onButtonUpObservable.clear();
  62900. };
  62901. return GenericPad;
  62902. }(Gamepad));
  62903. BABYLON.GenericPad = GenericPad;
  62904. })(BABYLON || (BABYLON = {}));
  62905. //# sourceMappingURL=babylon.gamepad.js.map
  62906. var BABYLON;
  62907. (function (BABYLON) {
  62908. var Xbox360Button;
  62909. (function (Xbox360Button) {
  62910. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  62911. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  62912. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  62913. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  62914. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  62915. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  62916. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  62917. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  62918. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  62919. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  62920. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  62921. var Xbox360Dpad;
  62922. (function (Xbox360Dpad) {
  62923. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  62924. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  62925. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  62926. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  62927. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  62928. var Xbox360Pad = /** @class */ (function (_super) {
  62929. __extends(Xbox360Pad, _super);
  62930. function Xbox360Pad(id, index, gamepad, xboxOne) {
  62931. if (xboxOne === void 0) { xboxOne = false; }
  62932. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  62933. _this._leftTrigger = 0;
  62934. _this._rightTrigger = 0;
  62935. _this.onButtonDownObservable = new BABYLON.Observable();
  62936. _this.onButtonUpObservable = new BABYLON.Observable();
  62937. _this.onPadDownObservable = new BABYLON.Observable();
  62938. _this.onPadUpObservable = new BABYLON.Observable();
  62939. _this._buttonA = 0;
  62940. _this._buttonB = 0;
  62941. _this._buttonX = 0;
  62942. _this._buttonY = 0;
  62943. _this._buttonBack = 0;
  62944. _this._buttonStart = 0;
  62945. _this._buttonLB = 0;
  62946. _this._buttonRB = 0;
  62947. _this._buttonLeftStick = 0;
  62948. _this._buttonRightStick = 0;
  62949. _this._dPadUp = 0;
  62950. _this._dPadDown = 0;
  62951. _this._dPadLeft = 0;
  62952. _this._dPadRight = 0;
  62953. _this._isXboxOnePad = false;
  62954. _this.type = BABYLON.Gamepad.XBOX;
  62955. _this._isXboxOnePad = xboxOne;
  62956. return _this;
  62957. }
  62958. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  62959. this._onlefttriggerchanged = callback;
  62960. };
  62961. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  62962. this._onrighttriggerchanged = callback;
  62963. };
  62964. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  62965. get: function () {
  62966. return this._leftTrigger;
  62967. },
  62968. set: function (newValue) {
  62969. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  62970. this._onlefttriggerchanged(newValue);
  62971. }
  62972. this._leftTrigger = newValue;
  62973. },
  62974. enumerable: true,
  62975. configurable: true
  62976. });
  62977. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  62978. get: function () {
  62979. return this._rightTrigger;
  62980. },
  62981. set: function (newValue) {
  62982. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  62983. this._onrighttriggerchanged(newValue);
  62984. }
  62985. this._rightTrigger = newValue;
  62986. },
  62987. enumerable: true,
  62988. configurable: true
  62989. });
  62990. Xbox360Pad.prototype.onbuttondown = function (callback) {
  62991. this._onbuttondown = callback;
  62992. };
  62993. Xbox360Pad.prototype.onbuttonup = function (callback) {
  62994. this._onbuttonup = callback;
  62995. };
  62996. Xbox360Pad.prototype.ondpaddown = function (callback) {
  62997. this._ondpaddown = callback;
  62998. };
  62999. Xbox360Pad.prototype.ondpadup = function (callback) {
  63000. this._ondpadup = callback;
  63001. };
  63002. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  63003. if (newValue !== currentValue) {
  63004. if (newValue === 1) {
  63005. if (this._onbuttondown) {
  63006. this._onbuttondown(buttonType);
  63007. }
  63008. this.onButtonDownObservable.notifyObservers(buttonType);
  63009. }
  63010. if (newValue === 0) {
  63011. if (this._onbuttonup) {
  63012. this._onbuttonup(buttonType);
  63013. }
  63014. this.onButtonUpObservable.notifyObservers(buttonType);
  63015. }
  63016. }
  63017. return newValue;
  63018. };
  63019. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  63020. if (newValue !== currentValue) {
  63021. if (newValue === 1) {
  63022. if (this._ondpaddown) {
  63023. this._ondpaddown(buttonType);
  63024. }
  63025. this.onPadDownObservable.notifyObservers(buttonType);
  63026. }
  63027. if (newValue === 0) {
  63028. if (this._ondpadup) {
  63029. this._ondpadup(buttonType);
  63030. }
  63031. this.onPadUpObservable.notifyObservers(buttonType);
  63032. }
  63033. }
  63034. return newValue;
  63035. };
  63036. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  63037. get: function () {
  63038. return this._buttonA;
  63039. },
  63040. set: function (value) {
  63041. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  63042. },
  63043. enumerable: true,
  63044. configurable: true
  63045. });
  63046. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  63047. get: function () {
  63048. return this._buttonB;
  63049. },
  63050. set: function (value) {
  63051. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  63052. },
  63053. enumerable: true,
  63054. configurable: true
  63055. });
  63056. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  63057. get: function () {
  63058. return this._buttonX;
  63059. },
  63060. set: function (value) {
  63061. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  63062. },
  63063. enumerable: true,
  63064. configurable: true
  63065. });
  63066. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  63067. get: function () {
  63068. return this._buttonY;
  63069. },
  63070. set: function (value) {
  63071. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  63072. },
  63073. enumerable: true,
  63074. configurable: true
  63075. });
  63076. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  63077. get: function () {
  63078. return this._buttonStart;
  63079. },
  63080. set: function (value) {
  63081. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  63082. },
  63083. enumerable: true,
  63084. configurable: true
  63085. });
  63086. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  63087. get: function () {
  63088. return this._buttonBack;
  63089. },
  63090. set: function (value) {
  63091. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  63092. },
  63093. enumerable: true,
  63094. configurable: true
  63095. });
  63096. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  63097. get: function () {
  63098. return this._buttonLB;
  63099. },
  63100. set: function (value) {
  63101. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  63102. },
  63103. enumerable: true,
  63104. configurable: true
  63105. });
  63106. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  63107. get: function () {
  63108. return this._buttonRB;
  63109. },
  63110. set: function (value) {
  63111. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  63112. },
  63113. enumerable: true,
  63114. configurable: true
  63115. });
  63116. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  63117. get: function () {
  63118. return this._buttonLeftStick;
  63119. },
  63120. set: function (value) {
  63121. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  63122. },
  63123. enumerable: true,
  63124. configurable: true
  63125. });
  63126. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  63127. get: function () {
  63128. return this._buttonRightStick;
  63129. },
  63130. set: function (value) {
  63131. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  63132. },
  63133. enumerable: true,
  63134. configurable: true
  63135. });
  63136. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  63137. get: function () {
  63138. return this._dPadUp;
  63139. },
  63140. set: function (value) {
  63141. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  63142. },
  63143. enumerable: true,
  63144. configurable: true
  63145. });
  63146. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  63147. get: function () {
  63148. return this._dPadDown;
  63149. },
  63150. set: function (value) {
  63151. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  63152. },
  63153. enumerable: true,
  63154. configurable: true
  63155. });
  63156. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  63157. get: function () {
  63158. return this._dPadLeft;
  63159. },
  63160. set: function (value) {
  63161. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  63162. },
  63163. enumerable: true,
  63164. configurable: true
  63165. });
  63166. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  63167. get: function () {
  63168. return this._dPadRight;
  63169. },
  63170. set: function (value) {
  63171. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  63172. },
  63173. enumerable: true,
  63174. configurable: true
  63175. });
  63176. Xbox360Pad.prototype.update = function () {
  63177. _super.prototype.update.call(this);
  63178. if (this._isXboxOnePad) {
  63179. this.buttonA = this.browserGamepad.buttons[0].value;
  63180. this.buttonB = this.browserGamepad.buttons[1].value;
  63181. this.buttonX = this.browserGamepad.buttons[2].value;
  63182. this.buttonY = this.browserGamepad.buttons[3].value;
  63183. this.buttonLB = this.browserGamepad.buttons[4].value;
  63184. this.buttonRB = this.browserGamepad.buttons[5].value;
  63185. this.leftTrigger = this.browserGamepad.axes[2];
  63186. this.rightTrigger = this.browserGamepad.axes[5];
  63187. this.buttonBack = this.browserGamepad.buttons[9].value;
  63188. this.buttonStart = this.browserGamepad.buttons[8].value;
  63189. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  63190. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  63191. this.dPadUp = this.browserGamepad.buttons[11].value;
  63192. this.dPadDown = this.browserGamepad.buttons[12].value;
  63193. this.dPadLeft = this.browserGamepad.buttons[13].value;
  63194. this.dPadRight = this.browserGamepad.buttons[14].value;
  63195. }
  63196. else {
  63197. this.buttonA = this.browserGamepad.buttons[0].value;
  63198. this.buttonB = this.browserGamepad.buttons[1].value;
  63199. this.buttonX = this.browserGamepad.buttons[2].value;
  63200. this.buttonY = this.browserGamepad.buttons[3].value;
  63201. this.buttonLB = this.browserGamepad.buttons[4].value;
  63202. this.buttonRB = this.browserGamepad.buttons[5].value;
  63203. this.leftTrigger = this.browserGamepad.buttons[6].value;
  63204. this.rightTrigger = this.browserGamepad.buttons[7].value;
  63205. this.buttonBack = this.browserGamepad.buttons[8].value;
  63206. this.buttonStart = this.browserGamepad.buttons[9].value;
  63207. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  63208. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  63209. this.dPadUp = this.browserGamepad.buttons[12].value;
  63210. this.dPadDown = this.browserGamepad.buttons[13].value;
  63211. this.dPadLeft = this.browserGamepad.buttons[14].value;
  63212. this.dPadRight = this.browserGamepad.buttons[15].value;
  63213. }
  63214. };
  63215. Xbox360Pad.prototype.dispose = function () {
  63216. _super.prototype.dispose.call(this);
  63217. this.onButtonDownObservable.clear();
  63218. this.onButtonUpObservable.clear();
  63219. this.onPadDownObservable.clear();
  63220. this.onPadUpObservable.clear();
  63221. };
  63222. return Xbox360Pad;
  63223. }(BABYLON.Gamepad));
  63224. BABYLON.Xbox360Pad = Xbox360Pad;
  63225. })(BABYLON || (BABYLON = {}));
  63226. //# sourceMappingURL=babylon.xboxGamepad.js.map
  63227. var BABYLON;
  63228. (function (BABYLON) {
  63229. var PoseEnabledControllerType;
  63230. (function (PoseEnabledControllerType) {
  63231. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  63232. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  63233. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  63234. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  63235. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  63236. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  63237. var PoseEnabledControllerHelper = /** @class */ (function () {
  63238. function PoseEnabledControllerHelper() {
  63239. }
  63240. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  63241. // Oculus Touch
  63242. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  63243. return new BABYLON.OculusTouchController(vrGamepad);
  63244. }
  63245. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  63246. return new BABYLON.WindowsMotionController(vrGamepad);
  63247. }
  63248. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  63249. return new BABYLON.ViveController(vrGamepad);
  63250. }
  63251. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  63252. return new BABYLON.GearVRController(vrGamepad);
  63253. }
  63254. else {
  63255. return new BABYLON.GenericController(vrGamepad);
  63256. }
  63257. };
  63258. return PoseEnabledControllerHelper;
  63259. }());
  63260. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  63261. var PoseEnabledController = /** @class */ (function (_super) {
  63262. __extends(PoseEnabledController, _super);
  63263. function PoseEnabledController(browserGamepad) {
  63264. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  63265. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  63266. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  63267. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  63268. // Represents device position and rotation in babylon space
  63269. _this.devicePosition = BABYLON.Vector3.Zero();
  63270. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63271. _this.deviceScaleFactor = 1;
  63272. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  63273. _this._deviceToWorld = BABYLON.Matrix.Identity();
  63274. _this._workingMatrix = BABYLON.Matrix.Identity();
  63275. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  63276. _this.controllerType = PoseEnabledControllerType.GENERIC;
  63277. _this.position = BABYLON.Vector3.Zero();
  63278. _this.rotationQuaternion = new BABYLON.Quaternion();
  63279. _this._calculatedPosition = BABYLON.Vector3.Zero();
  63280. _this._calculatedRotation = new BABYLON.Quaternion();
  63281. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  63282. return _this;
  63283. }
  63284. PoseEnabledController.prototype.update = function () {
  63285. _super.prototype.update.call(this);
  63286. var pose = this.browserGamepad.pose;
  63287. this.updateFromDevice(pose);
  63288. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  63289. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  63290. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  63291. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  63292. if (this._mesh) {
  63293. this._mesh.position.copyFrom(this.devicePosition);
  63294. if (this._mesh.rotationQuaternion) {
  63295. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63296. }
  63297. }
  63298. };
  63299. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  63300. if (poseData) {
  63301. this.rawPose = poseData;
  63302. if (poseData.position) {
  63303. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  63304. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  63305. this._deviceRoomPosition.z *= -1;
  63306. }
  63307. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  63308. this._calculatedPosition.addInPlace(this.position);
  63309. }
  63310. var pose = this.rawPose;
  63311. if (poseData.orientation && pose.orientation) {
  63312. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  63313. if (this._mesh) {
  63314. if (this._mesh.getScene().useRightHandedSystem) {
  63315. this._deviceRoomRotationQuaternion.z *= -1;
  63316. this._deviceRoomRotationQuaternion.w *= -1;
  63317. }
  63318. else {
  63319. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  63320. }
  63321. }
  63322. // if the camera is set, rotate to the camera's rotation
  63323. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  63324. }
  63325. }
  63326. };
  63327. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  63328. if (this._mesh) {
  63329. this._mesh.parent = null;
  63330. }
  63331. this._mesh = mesh;
  63332. if (this._poseControlledCamera) {
  63333. this._mesh.parent = this._poseControlledCamera;
  63334. }
  63335. if (!this._mesh.rotationQuaternion) {
  63336. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  63337. }
  63338. };
  63339. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  63340. this._poseControlledCamera = camera;
  63341. if (this._mesh) {
  63342. this._mesh.parent = this._poseControlledCamera;
  63343. }
  63344. };
  63345. PoseEnabledController.prototype.dispose = function () {
  63346. if (this._mesh) {
  63347. this._mesh.dispose();
  63348. }
  63349. this._mesh = null;
  63350. _super.prototype.dispose.call(this);
  63351. };
  63352. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  63353. get: function () {
  63354. return this._mesh;
  63355. },
  63356. enumerable: true,
  63357. configurable: true
  63358. });
  63359. PoseEnabledController.prototype.getForwardRay = function (length) {
  63360. if (length === void 0) { length = 100; }
  63361. if (!this.mesh) {
  63362. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  63363. }
  63364. var m = this.mesh.getWorldMatrix();
  63365. var origin = m.getTranslation();
  63366. var forward = new BABYLON.Vector3(0, 0, -1);
  63367. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63368. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63369. return new BABYLON.Ray(origin, direction, length);
  63370. };
  63371. return PoseEnabledController;
  63372. }(BABYLON.Gamepad));
  63373. BABYLON.PoseEnabledController = PoseEnabledController;
  63374. })(BABYLON || (BABYLON = {}));
  63375. //# sourceMappingURL=babylon.poseEnabledController.js.map
  63376. var BABYLON;
  63377. (function (BABYLON) {
  63378. var WebVRController = /** @class */ (function (_super) {
  63379. __extends(WebVRController, _super);
  63380. function WebVRController(vrGamepad) {
  63381. var _this = _super.call(this, vrGamepad) || this;
  63382. // Observables
  63383. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  63384. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  63385. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  63386. _this.onPadStateChangedObservable = new BABYLON.Observable();
  63387. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  63388. _this.pad = { x: 0, y: 0 };
  63389. // avoid GC, store state in a tmp object
  63390. _this._changes = {
  63391. pressChanged: false,
  63392. touchChanged: false,
  63393. valueChanged: false,
  63394. changed: false
  63395. };
  63396. _this._buttons = new Array(vrGamepad.buttons.length);
  63397. _this.hand = vrGamepad.hand;
  63398. return _this;
  63399. }
  63400. WebVRController.prototype.onButtonStateChange = function (callback) {
  63401. this._onButtonStateChange = callback;
  63402. };
  63403. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  63404. get: function () {
  63405. return this._defaultModel;
  63406. },
  63407. enumerable: true,
  63408. configurable: true
  63409. });
  63410. WebVRController.prototype.update = function () {
  63411. _super.prototype.update.call(this);
  63412. for (var index = 0; index < this._buttons.length; index++) {
  63413. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  63414. }
  63415. ;
  63416. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  63417. this.pad.x = this.leftStick.x;
  63418. this.pad.y = this.leftStick.y;
  63419. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  63420. }
  63421. };
  63422. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  63423. if (!newState) {
  63424. newState = {
  63425. pressed: false,
  63426. touched: false,
  63427. value: 0
  63428. };
  63429. }
  63430. if (!currentState) {
  63431. this._buttons[buttonIndex] = {
  63432. pressed: newState.pressed,
  63433. touched: newState.touched,
  63434. value: newState.value
  63435. };
  63436. return;
  63437. }
  63438. this._checkChanges(newState, currentState);
  63439. if (this._changes.changed) {
  63440. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  63441. this.handleButtonChange(buttonIndex, newState, this._changes);
  63442. }
  63443. this._buttons[buttonIndex].pressed = newState.pressed;
  63444. this._buttons[buttonIndex].touched = newState.touched;
  63445. // oculus triggers are never 0, thou not touched.
  63446. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  63447. };
  63448. WebVRController.prototype._checkChanges = function (newState, currentState) {
  63449. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  63450. this._changes.touchChanged = newState.touched !== currentState.touched;
  63451. this._changes.valueChanged = newState.value !== currentState.value;
  63452. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  63453. return this._changes;
  63454. };
  63455. WebVRController.prototype.dispose = function () {
  63456. _super.prototype.dispose.call(this);
  63457. this.onTriggerStateChangedObservable.clear();
  63458. this.onMainButtonStateChangedObservable.clear();
  63459. this.onSecondaryButtonStateChangedObservable.clear();
  63460. this.onPadStateChangedObservable.clear();
  63461. this.onPadValuesChangedObservable.clear();
  63462. };
  63463. return WebVRController;
  63464. }(BABYLON.PoseEnabledController));
  63465. BABYLON.WebVRController = WebVRController;
  63466. })(BABYLON || (BABYLON = {}));
  63467. //# sourceMappingURL=babylon.webVRController.js.map
  63468. var BABYLON;
  63469. (function (BABYLON) {
  63470. var OculusTouchController = /** @class */ (function (_super) {
  63471. __extends(OculusTouchController, _super);
  63472. function OculusTouchController(vrGamepad) {
  63473. var _this = _super.call(this, vrGamepad) || this;
  63474. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  63475. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  63476. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  63477. return _this;
  63478. }
  63479. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63480. var _this = this;
  63481. var meshName;
  63482. // Hand
  63483. if (this.hand === 'left') {
  63484. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  63485. }
  63486. else {
  63487. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  63488. }
  63489. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  63490. /*
  63491. Parent Mesh name: oculus_touch_left
  63492. - body
  63493. - trigger
  63494. - thumbstick
  63495. - grip
  63496. - button_y
  63497. - button_x
  63498. - button_enter
  63499. */
  63500. _this._defaultModel = newMeshes[1];
  63501. _this.attachToMesh(_this._defaultModel);
  63502. if (meshLoaded) {
  63503. meshLoaded(_this._defaultModel);
  63504. }
  63505. });
  63506. };
  63507. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  63508. // helper getters for left and right hand.
  63509. get: function () {
  63510. if (this.hand === 'right') {
  63511. return this.onMainButtonStateChangedObservable;
  63512. }
  63513. else {
  63514. throw new Error('No A button on left hand');
  63515. }
  63516. },
  63517. enumerable: true,
  63518. configurable: true
  63519. });
  63520. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  63521. get: function () {
  63522. if (this.hand === 'right') {
  63523. return this.onSecondaryButtonStateChangedObservable;
  63524. }
  63525. else {
  63526. throw new Error('No B button on left hand');
  63527. }
  63528. },
  63529. enumerable: true,
  63530. configurable: true
  63531. });
  63532. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  63533. get: function () {
  63534. if (this.hand === 'left') {
  63535. return this.onMainButtonStateChangedObservable;
  63536. }
  63537. else {
  63538. throw new Error('No X button on right hand');
  63539. }
  63540. },
  63541. enumerable: true,
  63542. configurable: true
  63543. });
  63544. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  63545. get: function () {
  63546. if (this.hand === 'left') {
  63547. return this.onSecondaryButtonStateChangedObservable;
  63548. }
  63549. else {
  63550. throw new Error('No Y button on right hand');
  63551. }
  63552. },
  63553. enumerable: true,
  63554. configurable: true
  63555. });
  63556. /*
  63557. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  63558. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  63559. 2) secondary trigger (same)
  63560. 3) A (right) X (left), touch, pressed = value
  63561. 4) B / Y
  63562. 5) thumb rest
  63563. */
  63564. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63565. var notifyObject = state; //{ state: state, changes: changes };
  63566. var triggerDirection = this.hand === 'right' ? -1 : 1;
  63567. switch (buttonIdx) {
  63568. case 0:
  63569. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63570. return;
  63571. case 1:// index trigger
  63572. if (this._defaultModel) {
  63573. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  63574. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  63575. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  63576. }
  63577. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63578. return;
  63579. case 2:// secondary trigger
  63580. if (this._defaultModel) {
  63581. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  63582. }
  63583. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  63584. return;
  63585. case 3:
  63586. if (this._defaultModel) {
  63587. if (notifyObject.pressed) {
  63588. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  63589. }
  63590. else {
  63591. (this._defaultModel.getChildren()[1]).position.y = 0;
  63592. }
  63593. }
  63594. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63595. return;
  63596. case 4:
  63597. if (this._defaultModel) {
  63598. if (notifyObject.pressed) {
  63599. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63600. }
  63601. else {
  63602. (this._defaultModel.getChildren()[2]).position.y = 0;
  63603. }
  63604. }
  63605. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63606. return;
  63607. case 5:
  63608. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  63609. return;
  63610. }
  63611. };
  63612. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  63613. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  63614. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  63615. return OculusTouchController;
  63616. }(BABYLON.WebVRController));
  63617. BABYLON.OculusTouchController = OculusTouchController;
  63618. })(BABYLON || (BABYLON = {}));
  63619. //# sourceMappingURL=babylon.oculusTouchController.js.map
  63620. var BABYLON;
  63621. (function (BABYLON) {
  63622. var ViveController = /** @class */ (function (_super) {
  63623. __extends(ViveController, _super);
  63624. function ViveController(vrGamepad) {
  63625. var _this = _super.call(this, vrGamepad) || this;
  63626. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  63627. _this._invertLeftStickY = true;
  63628. return _this;
  63629. }
  63630. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63631. var _this = this;
  63632. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  63633. /*
  63634. Parent Mesh name: ViveWand
  63635. - body
  63636. - r_gripper
  63637. - l_gripper
  63638. - menu_button
  63639. - system_button
  63640. - trackpad
  63641. - trigger
  63642. - LED
  63643. */
  63644. _this._defaultModel = newMeshes[1];
  63645. _this.attachToMesh(_this._defaultModel);
  63646. if (meshLoaded) {
  63647. meshLoaded(_this._defaultModel);
  63648. }
  63649. });
  63650. };
  63651. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  63652. get: function () {
  63653. return this.onMainButtonStateChangedObservable;
  63654. },
  63655. enumerable: true,
  63656. configurable: true
  63657. });
  63658. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  63659. get: function () {
  63660. return this.onMainButtonStateChangedObservable;
  63661. },
  63662. enumerable: true,
  63663. configurable: true
  63664. });
  63665. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  63666. get: function () {
  63667. return this.onSecondaryButtonStateChangedObservable;
  63668. },
  63669. enumerable: true,
  63670. configurable: true
  63671. });
  63672. /**
  63673. * Vive mapping:
  63674. * 0: touchpad
  63675. * 1: trigger
  63676. * 2: left AND right buttons
  63677. * 3: menu button
  63678. */
  63679. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63680. var notifyObject = state; //{ state: state, changes: changes };
  63681. switch (buttonIdx) {
  63682. case 0:
  63683. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63684. return;
  63685. case 1:// index trigger
  63686. if (this._defaultModel) {
  63687. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  63688. }
  63689. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63690. return;
  63691. case 2:// left AND right button
  63692. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63693. return;
  63694. case 3:
  63695. if (this._defaultModel) {
  63696. if (notifyObject.pressed) {
  63697. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63698. }
  63699. else {
  63700. (this._defaultModel.getChildren()[2]).position.y = 0;
  63701. }
  63702. }
  63703. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63704. return;
  63705. }
  63706. };
  63707. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  63708. ViveController.MODEL_FILENAME = 'wand.babylon';
  63709. return ViveController;
  63710. }(BABYLON.WebVRController));
  63711. BABYLON.ViveController = ViveController;
  63712. })(BABYLON || (BABYLON = {}));
  63713. //# sourceMappingURL=babylon.viveController.js.map
  63714. var BABYLON;
  63715. (function (BABYLON) {
  63716. var GenericController = /** @class */ (function (_super) {
  63717. __extends(GenericController, _super);
  63718. function GenericController(vrGamepad) {
  63719. return _super.call(this, vrGamepad) || this;
  63720. }
  63721. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63722. var _this = this;
  63723. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  63724. _this._defaultModel = newMeshes[1];
  63725. _this.attachToMesh(_this._defaultModel);
  63726. if (meshLoaded) {
  63727. meshLoaded(_this._defaultModel);
  63728. }
  63729. });
  63730. };
  63731. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63732. console.log("Button id: " + buttonIdx + "state: ");
  63733. console.dir(state);
  63734. };
  63735. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63736. GenericController.MODEL_FILENAME = 'generic.babylon';
  63737. return GenericController;
  63738. }(BABYLON.WebVRController));
  63739. BABYLON.GenericController = GenericController;
  63740. })(BABYLON || (BABYLON = {}));
  63741. //# sourceMappingURL=babylon.genericController.js.map
  63742. var BABYLON;
  63743. (function (BABYLON) {
  63744. var LoadedMeshInfo = /** @class */ (function () {
  63745. function LoadedMeshInfo() {
  63746. this.buttonMeshes = {};
  63747. this.axisMeshes = {};
  63748. }
  63749. return LoadedMeshInfo;
  63750. }());
  63751. var WindowsMotionController = /** @class */ (function (_super) {
  63752. __extends(WindowsMotionController, _super);
  63753. function WindowsMotionController(vrGamepad) {
  63754. var _this = _super.call(this, vrGamepad) || this;
  63755. _this._mapping = {
  63756. // Semantic button names
  63757. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  63758. // A mapping of the button name to glTF model node name
  63759. // that should be transformed by button value.
  63760. buttonMeshNames: {
  63761. 'trigger': 'SELECT',
  63762. 'menu': 'MENU',
  63763. 'grip': 'GRASP',
  63764. 'thumbstick': 'THUMBSTICK_PRESS',
  63765. 'trackpad': 'TOUCHPAD_PRESS'
  63766. },
  63767. // This mapping is used to translate from the Motion Controller to Babylon semantics
  63768. buttonObservableNames: {
  63769. 'trigger': 'onTriggerStateChangedObservable',
  63770. 'menu': 'onSecondaryButtonStateChangedObservable',
  63771. 'grip': 'onMainButtonStateChangedObservable',
  63772. 'thumbstick': 'onPadStateChangedObservable',
  63773. 'trackpad': 'onTrackpadChangedObservable'
  63774. },
  63775. // A mapping of the axis name to glTF model node name
  63776. // that should be transformed by axis value.
  63777. // This array mirrors the browserGamepad.axes array, such that
  63778. // the mesh corresponding to axis 0 is in this array index 0.
  63779. axisMeshNames: [
  63780. 'THUMBSTICK_X',
  63781. 'THUMBSTICK_Y',
  63782. 'TOUCHPAD_TOUCH_X',
  63783. 'TOUCHPAD_TOUCH_Y'
  63784. ],
  63785. pointingPoseMeshName: 'POINTING_POSE'
  63786. };
  63787. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  63788. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  63789. _this.trackpad = { x: 0, y: 0 };
  63790. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  63791. _this._loadedMeshInfo = null;
  63792. return _this;
  63793. }
  63794. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  63795. get: function () {
  63796. return this.onTriggerStateChangedObservable;
  63797. },
  63798. enumerable: true,
  63799. configurable: true
  63800. });
  63801. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  63802. get: function () {
  63803. return this.onSecondaryButtonStateChangedObservable;
  63804. },
  63805. enumerable: true,
  63806. configurable: true
  63807. });
  63808. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  63809. get: function () {
  63810. return this.onMainButtonStateChangedObservable;
  63811. },
  63812. enumerable: true,
  63813. configurable: true
  63814. });
  63815. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  63816. get: function () {
  63817. return this.onPadStateChangedObservable;
  63818. },
  63819. enumerable: true,
  63820. configurable: true
  63821. });
  63822. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  63823. get: function () {
  63824. return this.onTrackpadChangedObservable;
  63825. },
  63826. enumerable: true,
  63827. configurable: true
  63828. });
  63829. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  63830. get: function () {
  63831. return this.onTrackpadValuesChangedObservable;
  63832. },
  63833. enumerable: true,
  63834. configurable: true
  63835. });
  63836. /**
  63837. * Called once per frame by the engine.
  63838. */
  63839. WindowsMotionController.prototype.update = function () {
  63840. _super.prototype.update.call(this);
  63841. // Only need to animate axes if there is a loaded mesh
  63842. if (this._loadedMeshInfo) {
  63843. if (this.browserGamepad.axes) {
  63844. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  63845. this.trackpad.x = this.browserGamepad["axes"][2];
  63846. this.trackpad.y = this.browserGamepad["axes"][3];
  63847. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  63848. }
  63849. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  63850. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  63851. }
  63852. }
  63853. }
  63854. };
  63855. /**
  63856. * Called once for each button that changed state since the last frame
  63857. * @param buttonIdx Which button index changed
  63858. * @param state New state of the button
  63859. * @param changes Which properties on the state changed since last frame
  63860. */
  63861. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63862. var buttonName = this._mapping.buttons[buttonIdx];
  63863. if (!buttonName) {
  63864. return;
  63865. }
  63866. // Only emit events for buttons that we know how to map from index to name
  63867. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  63868. if (observable) {
  63869. observable.notifyObservers(state);
  63870. }
  63871. this.lerpButtonTransform(buttonName, state.value);
  63872. };
  63873. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  63874. // If there is no loaded mesh, there is nothing to transform.
  63875. if (!this._loadedMeshInfo) {
  63876. return;
  63877. }
  63878. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  63879. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63880. return;
  63881. }
  63882. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  63883. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  63884. };
  63885. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  63886. if (!this._loadedMeshInfo) {
  63887. return;
  63888. }
  63889. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  63890. if (!meshInfo) {
  63891. return;
  63892. }
  63893. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63894. return;
  63895. }
  63896. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  63897. var lerpValue = axisValue * 0.5 + 0.5;
  63898. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  63899. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  63900. };
  63901. /**
  63902. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  63903. * @param scene scene in which to add meshes
  63904. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  63905. */
  63906. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  63907. var _this = this;
  63908. if (forceDefault === void 0) { forceDefault = false; }
  63909. var path;
  63910. var filename;
  63911. // Checking if GLB loader is present
  63912. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  63913. // Determine the device specific folder based on the ID suffix
  63914. var device = 'default';
  63915. if (this.id && !forceDefault) {
  63916. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  63917. device = ((match && match[0]) || device);
  63918. }
  63919. // Hand
  63920. if (this.hand === 'left') {
  63921. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  63922. }
  63923. else {
  63924. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  63925. }
  63926. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  63927. }
  63928. else {
  63929. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  63930. path = BABYLON.GenericController.MODEL_BASE_URL;
  63931. filename = BABYLON.GenericController.MODEL_FILENAME;
  63932. }
  63933. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  63934. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  63935. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  63936. if (!_this._loadedMeshInfo) {
  63937. return;
  63938. }
  63939. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  63940. _this.attachToMesh(_this._defaultModel);
  63941. if (meshLoaded) {
  63942. meshLoaded(_this._defaultModel);
  63943. }
  63944. }, null, function (scene, message) {
  63945. BABYLON.Tools.Log(message);
  63946. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  63947. if (!forceDefault) {
  63948. _this.initControllerMesh(scene, meshLoaded, true);
  63949. }
  63950. });
  63951. };
  63952. /**
  63953. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  63954. * can be transformed by button presses and axes values, based on this._mapping.
  63955. *
  63956. * @param scene scene in which the meshes exist
  63957. * @param meshes list of meshes that make up the controller model to process
  63958. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  63959. */
  63960. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  63961. var loadedMeshInfo = null;
  63962. // Create a new mesh to contain the glTF hierarchy
  63963. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  63964. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  63965. var childMesh = null;
  63966. for (var i = 0; i < meshes.length; i++) {
  63967. var mesh = meshes[i];
  63968. if (!mesh.parent) {
  63969. // Exclude controller meshes from picking results
  63970. mesh.isPickable = false;
  63971. // Handle root node, attach to the new parentMesh
  63972. childMesh = mesh;
  63973. break;
  63974. }
  63975. }
  63976. if (childMesh) {
  63977. childMesh.setParent(parentMesh);
  63978. // Create our mesh info. Note that this method will always return non-null.
  63979. loadedMeshInfo = this.createMeshInfo(parentMesh);
  63980. }
  63981. else {
  63982. BABYLON.Tools.Warn('Could not find root node in model file.');
  63983. }
  63984. return loadedMeshInfo;
  63985. };
  63986. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  63987. var loadedMeshInfo = new LoadedMeshInfo();
  63988. var i;
  63989. loadedMeshInfo.rootNode = rootNode;
  63990. // Reset the caches
  63991. loadedMeshInfo.buttonMeshes = {};
  63992. loadedMeshInfo.axisMeshes = {};
  63993. // Button Meshes
  63994. for (i = 0; i < this._mapping.buttons.length; i++) {
  63995. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  63996. if (!buttonMeshName) {
  63997. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  63998. continue;
  63999. }
  64000. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  64001. if (!buttonMesh) {
  64002. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  64003. continue;
  64004. }
  64005. var buttonMeshInfo = {
  64006. index: i,
  64007. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  64008. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  64009. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  64010. };
  64011. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  64012. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  64013. }
  64014. else {
  64015. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  64016. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  64017. '(VALUE: ' + !!buttonMeshInfo.value +
  64018. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  64019. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  64020. ')');
  64021. }
  64022. }
  64023. // Axis Meshes
  64024. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  64025. var axisMeshName = this._mapping.axisMeshNames[i];
  64026. if (!axisMeshName) {
  64027. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  64028. continue;
  64029. }
  64030. var axisMesh = getChildByName(rootNode, axisMeshName);
  64031. if (!axisMesh) {
  64032. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  64033. continue;
  64034. }
  64035. var axisMeshInfo = {
  64036. index: i,
  64037. value: getImmediateChildByName(axisMesh, 'VALUE'),
  64038. min: getImmediateChildByName(axisMesh, 'MIN'),
  64039. max: getImmediateChildByName(axisMesh, 'MAX')
  64040. };
  64041. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  64042. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  64043. }
  64044. else {
  64045. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  64046. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  64047. '(VALUE: ' + !!axisMeshInfo.value +
  64048. ', MIN: ' + !!axisMeshInfo.min +
  64049. ', MAX:' + !!axisMeshInfo.max +
  64050. ')');
  64051. }
  64052. }
  64053. // Pointing Ray
  64054. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  64055. if (!loadedMeshInfo.pointingPoseNode) {
  64056. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  64057. }
  64058. return loadedMeshInfo;
  64059. // Look through all children recursively. This will return null if no mesh exists with the given name.
  64060. function getChildByName(node, name) {
  64061. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  64062. }
  64063. // Look through only immediate children. This will return null if no mesh exists with the given name.
  64064. function getImmediateChildByName(node, name) {
  64065. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  64066. }
  64067. };
  64068. WindowsMotionController.prototype.getForwardRay = function (length) {
  64069. if (length === void 0) { length = 100; }
  64070. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  64071. return _super.prototype.getForwardRay.call(this, length);
  64072. }
  64073. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  64074. var origin = m.getTranslation();
  64075. var forward = new BABYLON.Vector3(0, 0, -1);
  64076. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64077. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64078. return new BABYLON.Ray(origin, direction, length);
  64079. };
  64080. WindowsMotionController.prototype.dispose = function () {
  64081. _super.prototype.dispose.call(this);
  64082. this.onTrackpadChangedObservable.clear();
  64083. };
  64084. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  64085. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  64086. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  64087. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  64088. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  64089. return WindowsMotionController;
  64090. }(BABYLON.WebVRController));
  64091. BABYLON.WindowsMotionController = WindowsMotionController;
  64092. })(BABYLON || (BABYLON = {}));
  64093. //# sourceMappingURL=babylon.windowsMotionController.js.map
  64094. var BABYLON;
  64095. (function (BABYLON) {
  64096. var GearVRController = /** @class */ (function (_super) {
  64097. __extends(GearVRController, _super);
  64098. function GearVRController(vrGamepad) {
  64099. var _this = _super.call(this, vrGamepad) || this;
  64100. _this._buttonIndexToObservableNameMap = [
  64101. 'onTrackpadChangedObservable',
  64102. 'onTriggerStateChangedObservable' // Trigger
  64103. ];
  64104. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  64105. return _this;
  64106. }
  64107. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64108. var _this = this;
  64109. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  64110. _this._defaultModel = newMeshes[1];
  64111. _this.attachToMesh(_this._defaultModel);
  64112. if (meshLoaded) {
  64113. meshLoaded(_this._defaultModel);
  64114. }
  64115. });
  64116. };
  64117. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64118. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  64119. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  64120. // Only emit events for buttons that we know how to map from index to observable
  64121. var observable = this[observableName];
  64122. if (observable) {
  64123. observable.notifyObservers(state);
  64124. }
  64125. }
  64126. };
  64127. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64128. GearVRController.MODEL_FILENAME = 'generic.babylon';
  64129. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  64130. return GearVRController;
  64131. }(BABYLON.WebVRController));
  64132. BABYLON.GearVRController = GearVRController;
  64133. })(BABYLON || (BABYLON = {}));
  64134. //# sourceMappingURL=babylon.gearVRController.js.map
  64135. var BABYLON;
  64136. (function (BABYLON) {
  64137. var FollowCamera = /** @class */ (function (_super) {
  64138. __extends(FollowCamera, _super);
  64139. function FollowCamera(name, position, scene, lockedTarget) {
  64140. if (lockedTarget === void 0) { lockedTarget = null; }
  64141. var _this = _super.call(this, name, position, scene) || this;
  64142. _this.radius = 12;
  64143. _this.rotationOffset = 0;
  64144. _this.heightOffset = 4;
  64145. _this.cameraAcceleration = 0.05;
  64146. _this.maxCameraSpeed = 20;
  64147. _this.lockedTarget = lockedTarget;
  64148. return _this;
  64149. }
  64150. FollowCamera.prototype.getRadians = function (degrees) {
  64151. return degrees * Math.PI / 180;
  64152. };
  64153. FollowCamera.prototype.follow = function (cameraTarget) {
  64154. if (!cameraTarget)
  64155. return;
  64156. var yRotation;
  64157. if (cameraTarget.rotationQuaternion) {
  64158. var rotMatrix = new BABYLON.Matrix();
  64159. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  64160. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  64161. }
  64162. else {
  64163. yRotation = cameraTarget.rotation.y;
  64164. }
  64165. var radians = this.getRadians(this.rotationOffset) + yRotation;
  64166. var targetPosition = cameraTarget.getAbsolutePosition();
  64167. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  64168. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  64169. var dx = targetX - this.position.x;
  64170. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  64171. var dz = (targetZ) - this.position.z;
  64172. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  64173. var vy = dy * this.cameraAcceleration;
  64174. var vz = dz * this.cameraAcceleration * 2;
  64175. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  64176. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64177. }
  64178. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  64179. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64180. }
  64181. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  64182. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64183. }
  64184. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  64185. this.setTarget(targetPosition);
  64186. };
  64187. FollowCamera.prototype._checkInputs = function () {
  64188. _super.prototype._checkInputs.call(this);
  64189. if (this.lockedTarget) {
  64190. this.follow(this.lockedTarget);
  64191. }
  64192. };
  64193. FollowCamera.prototype.getClassName = function () {
  64194. return "FollowCamera";
  64195. };
  64196. __decorate([
  64197. BABYLON.serialize()
  64198. ], FollowCamera.prototype, "radius", void 0);
  64199. __decorate([
  64200. BABYLON.serialize()
  64201. ], FollowCamera.prototype, "rotationOffset", void 0);
  64202. __decorate([
  64203. BABYLON.serialize()
  64204. ], FollowCamera.prototype, "heightOffset", void 0);
  64205. __decorate([
  64206. BABYLON.serialize()
  64207. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  64208. __decorate([
  64209. BABYLON.serialize()
  64210. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  64211. __decorate([
  64212. BABYLON.serializeAsMeshReference("lockedTargetId")
  64213. ], FollowCamera.prototype, "lockedTarget", void 0);
  64214. return FollowCamera;
  64215. }(BABYLON.TargetCamera));
  64216. BABYLON.FollowCamera = FollowCamera;
  64217. var ArcFollowCamera = /** @class */ (function (_super) {
  64218. __extends(ArcFollowCamera, _super);
  64219. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  64220. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  64221. _this.alpha = alpha;
  64222. _this.beta = beta;
  64223. _this.radius = radius;
  64224. _this.target = target;
  64225. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  64226. _this.follow();
  64227. return _this;
  64228. }
  64229. ArcFollowCamera.prototype.follow = function () {
  64230. if (!this.target) {
  64231. return;
  64232. }
  64233. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  64234. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  64235. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  64236. var targetPosition = this.target.getAbsolutePosition();
  64237. this.position = targetPosition.add(this._cartesianCoordinates);
  64238. this.setTarget(targetPosition);
  64239. };
  64240. ArcFollowCamera.prototype._checkInputs = function () {
  64241. _super.prototype._checkInputs.call(this);
  64242. this.follow();
  64243. };
  64244. ArcFollowCamera.prototype.getClassName = function () {
  64245. return "ArcFollowCamera";
  64246. };
  64247. return ArcFollowCamera;
  64248. }(BABYLON.TargetCamera));
  64249. BABYLON.ArcFollowCamera = ArcFollowCamera;
  64250. })(BABYLON || (BABYLON = {}));
  64251. //# sourceMappingURL=babylon.followCamera.js.map
  64252. var BABYLON;
  64253. (function (BABYLON) {
  64254. // We're mainly based on the logic defined into the FreeCamera code
  64255. var UniversalCamera = /** @class */ (function (_super) {
  64256. __extends(UniversalCamera, _super);
  64257. //-- end properties for backward compatibility for inputs
  64258. function UniversalCamera(name, position, scene) {
  64259. var _this = _super.call(this, name, position, scene) || this;
  64260. _this.inputs.addGamepad();
  64261. return _this;
  64262. }
  64263. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  64264. //-- Begin properties for backward compatibility for inputs
  64265. get: function () {
  64266. var gamepad = this.inputs.attached["gamepad"];
  64267. if (gamepad)
  64268. return gamepad.gamepadAngularSensibility;
  64269. return 0;
  64270. },
  64271. set: function (value) {
  64272. var gamepad = this.inputs.attached["gamepad"];
  64273. if (gamepad)
  64274. gamepad.gamepadAngularSensibility = value;
  64275. },
  64276. enumerable: true,
  64277. configurable: true
  64278. });
  64279. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  64280. get: function () {
  64281. var gamepad = this.inputs.attached["gamepad"];
  64282. if (gamepad)
  64283. return gamepad.gamepadMoveSensibility;
  64284. return 0;
  64285. },
  64286. set: function (value) {
  64287. var gamepad = this.inputs.attached["gamepad"];
  64288. if (gamepad)
  64289. gamepad.gamepadMoveSensibility = value;
  64290. },
  64291. enumerable: true,
  64292. configurable: true
  64293. });
  64294. UniversalCamera.prototype.getClassName = function () {
  64295. return "UniversalCamera";
  64296. };
  64297. return UniversalCamera;
  64298. }(BABYLON.TouchCamera));
  64299. BABYLON.UniversalCamera = UniversalCamera;
  64300. })(BABYLON || (BABYLON = {}));
  64301. //# sourceMappingURL=babylon.universalCamera.js.map
  64302. var BABYLON;
  64303. (function (BABYLON) {
  64304. // We're mainly based on the logic defined into the FreeCamera code
  64305. var GamepadCamera = /** @class */ (function (_super) {
  64306. __extends(GamepadCamera, _super);
  64307. //-- end properties for backward compatibility for inputs
  64308. function GamepadCamera(name, position, scene) {
  64309. return _super.call(this, name, position, scene) || this;
  64310. }
  64311. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  64312. //-- Begin properties for backward compatibility for inputs
  64313. get: function () {
  64314. var gamepad = this.inputs.attached["gamepad"];
  64315. if (gamepad)
  64316. return gamepad.gamepadAngularSensibility;
  64317. return 0;
  64318. },
  64319. set: function (value) {
  64320. var gamepad = this.inputs.attached["gamepad"];
  64321. if (gamepad)
  64322. gamepad.gamepadAngularSensibility = value;
  64323. },
  64324. enumerable: true,
  64325. configurable: true
  64326. });
  64327. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  64328. get: function () {
  64329. var gamepad = this.inputs.attached["gamepad"];
  64330. if (gamepad)
  64331. return gamepad.gamepadMoveSensibility;
  64332. return 0;
  64333. },
  64334. set: function (value) {
  64335. var gamepad = this.inputs.attached["gamepad"];
  64336. if (gamepad)
  64337. gamepad.gamepadMoveSensibility = value;
  64338. },
  64339. enumerable: true,
  64340. configurable: true
  64341. });
  64342. GamepadCamera.prototype.getClassName = function () {
  64343. return "GamepadCamera";
  64344. };
  64345. return GamepadCamera;
  64346. }(BABYLON.UniversalCamera));
  64347. BABYLON.GamepadCamera = GamepadCamera;
  64348. })(BABYLON || (BABYLON = {}));
  64349. //# sourceMappingURL=babylon.gamepadCamera.js.map
  64350. var BABYLON;
  64351. (function (BABYLON) {
  64352. var PostProcessRenderPipelineManager = /** @class */ (function () {
  64353. function PostProcessRenderPipelineManager() {
  64354. this._renderPipelines = {};
  64355. }
  64356. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  64357. this._renderPipelines[renderPipeline._name] = renderPipeline;
  64358. };
  64359. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  64360. if (unique === void 0) { unique = false; }
  64361. var renderPipeline = this._renderPipelines[renderPipelineName];
  64362. if (!renderPipeline) {
  64363. return;
  64364. }
  64365. renderPipeline._attachCameras(cameras, unique);
  64366. };
  64367. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  64368. var renderPipeline = this._renderPipelines[renderPipelineName];
  64369. if (!renderPipeline) {
  64370. return;
  64371. }
  64372. renderPipeline._detachCameras(cameras);
  64373. };
  64374. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64375. var renderPipeline = this._renderPipelines[renderPipelineName];
  64376. if (!renderPipeline) {
  64377. return;
  64378. }
  64379. renderPipeline._enableEffect(renderEffectName, cameras);
  64380. };
  64381. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64382. var renderPipeline = this._renderPipelines[renderPipelineName];
  64383. if (!renderPipeline) {
  64384. return;
  64385. }
  64386. renderPipeline._disableEffect(renderEffectName, cameras);
  64387. };
  64388. PostProcessRenderPipelineManager.prototype.update = function () {
  64389. for (var renderPipelineName in this._renderPipelines) {
  64390. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64391. var pipeline = this._renderPipelines[renderPipelineName];
  64392. if (!pipeline.isSupported) {
  64393. pipeline.dispose();
  64394. delete this._renderPipelines[renderPipelineName];
  64395. }
  64396. else {
  64397. pipeline._update();
  64398. }
  64399. }
  64400. }
  64401. };
  64402. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  64403. for (var renderPipelineName in this._renderPipelines) {
  64404. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64405. var pipeline = this._renderPipelines[renderPipelineName];
  64406. pipeline._rebuild();
  64407. }
  64408. }
  64409. };
  64410. PostProcessRenderPipelineManager.prototype.dispose = function () {
  64411. for (var renderPipelineName in this._renderPipelines) {
  64412. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64413. var pipeline = this._renderPipelines[renderPipelineName];
  64414. pipeline.dispose();
  64415. }
  64416. }
  64417. };
  64418. return PostProcessRenderPipelineManager;
  64419. }());
  64420. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  64421. })(BABYLON || (BABYLON = {}));
  64422. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  64423. var BABYLON;
  64424. (function (BABYLON) {
  64425. /**
  64426. * This represents a set of one or more post processes in Babylon.
  64427. * A post process can be used to apply a shader to a texture after it is rendered.
  64428. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  64429. */
  64430. var PostProcessRenderEffect = /** @class */ (function () {
  64431. /**
  64432. * Instantiates a post process render effect.
  64433. * A post process can be used to apply a shader to a texture after it is rendered.
  64434. * @param engine The engine the effect is tied to
  64435. * @param name The name of the effect
  64436. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  64437. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  64438. */
  64439. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  64440. this._name = name;
  64441. this._singleInstance = singleInstance || true;
  64442. this._getPostProcesses = getPostProcesses;
  64443. this._cameras = {};
  64444. this._indicesForCamera = {};
  64445. this._postProcesses = {};
  64446. }
  64447. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  64448. /**
  64449. * Checks if all the post processes in the effect are supported.
  64450. */
  64451. get: function () {
  64452. for (var index in this._postProcesses) {
  64453. for (var ppIndex in this._postProcesses[index]) {
  64454. if (!this._postProcesses[index][ppIndex].isSupported) {
  64455. return false;
  64456. }
  64457. }
  64458. }
  64459. return true;
  64460. },
  64461. enumerable: true,
  64462. configurable: true
  64463. });
  64464. /**
  64465. * Updates the current state of the effect
  64466. */
  64467. PostProcessRenderEffect.prototype._update = function () {
  64468. };
  64469. /**
  64470. * Attaches the effect on cameras
  64471. * @param cameras The camera to attach to.
  64472. */
  64473. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  64474. var _this = this;
  64475. var cameraKey;
  64476. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64477. if (!cams) {
  64478. return;
  64479. }
  64480. for (var i = 0; i < cams.length; i++) {
  64481. var camera = cams[i];
  64482. var cameraName = camera.name;
  64483. if (this._singleInstance) {
  64484. cameraKey = 0;
  64485. }
  64486. else {
  64487. cameraKey = cameraName;
  64488. }
  64489. if (!this._postProcesses[cameraKey]) {
  64490. var postProcess = this._getPostProcesses();
  64491. if (postProcess) {
  64492. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  64493. }
  64494. }
  64495. if (!this._indicesForCamera[cameraName]) {
  64496. this._indicesForCamera[cameraName] = [];
  64497. }
  64498. this._postProcesses[cameraKey].forEach(function (postProcess) {
  64499. var index = camera.attachPostProcess(postProcess);
  64500. _this._indicesForCamera[cameraName].push(index);
  64501. });
  64502. if (!this._cameras[cameraName]) {
  64503. this._cameras[cameraName] = camera;
  64504. }
  64505. }
  64506. };
  64507. /**
  64508. * Detatches the effect on cameras
  64509. * @param cameras The camera to detatch from.
  64510. */
  64511. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  64512. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64513. if (!cams) {
  64514. return;
  64515. }
  64516. for (var i = 0; i < cams.length; i++) {
  64517. var camera = cams[i];
  64518. var cameraName = camera.name;
  64519. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64520. camera.detachPostProcess(postProcess);
  64521. });
  64522. if (this._cameras[cameraName]) {
  64523. //this._indicesForCamera.splice(index, 1);
  64524. this._cameras[cameraName] = null;
  64525. }
  64526. }
  64527. };
  64528. /**
  64529. * Enables the effect on given cameras
  64530. * @param cameras The camera to enable.
  64531. */
  64532. PostProcessRenderEffect.prototype._enable = function (cameras) {
  64533. var _this = this;
  64534. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64535. if (!cams) {
  64536. return;
  64537. }
  64538. for (var i = 0; i < cams.length; i++) {
  64539. var camera = cams[i];
  64540. var cameraName = camera.name;
  64541. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  64542. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  64543. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64544. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  64545. });
  64546. }
  64547. }
  64548. }
  64549. };
  64550. /**
  64551. * Disables the effect on the given cameras
  64552. * @param cameras The camera to disable.
  64553. */
  64554. PostProcessRenderEffect.prototype._disable = function (cameras) {
  64555. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64556. if (!cams) {
  64557. return;
  64558. }
  64559. for (var i = 0; i < cams.length; i++) {
  64560. var camera = cams[i];
  64561. var cameraName = camera.name;
  64562. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64563. camera.detachPostProcess(postProcess);
  64564. });
  64565. }
  64566. };
  64567. /**
  64568. * Gets a list of the post processes contained in the effect.
  64569. * @param camera The camera to get the post processes on.
  64570. * @returns The list of the post processes in the effect.
  64571. */
  64572. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  64573. if (this._singleInstance) {
  64574. return this._postProcesses[0];
  64575. }
  64576. else {
  64577. if (!camera) {
  64578. return null;
  64579. }
  64580. return this._postProcesses[camera.name];
  64581. }
  64582. };
  64583. return PostProcessRenderEffect;
  64584. }());
  64585. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  64586. })(BABYLON || (BABYLON = {}));
  64587. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  64588. var BABYLON;
  64589. (function (BABYLON) {
  64590. var PostProcessRenderPipeline = /** @class */ (function () {
  64591. function PostProcessRenderPipeline(engine, name) {
  64592. this._name = name;
  64593. this._renderEffects = {};
  64594. this._renderEffectsForIsolatedPass = new Array();
  64595. this._cameras = [];
  64596. }
  64597. PostProcessRenderPipeline.prototype.getClassName = function () {
  64598. return "PostProcessRenderPipeline";
  64599. };
  64600. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  64601. get: function () {
  64602. for (var renderEffectName in this._renderEffects) {
  64603. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64604. if (!this._renderEffects[renderEffectName].isSupported) {
  64605. return false;
  64606. }
  64607. }
  64608. }
  64609. return true;
  64610. },
  64611. enumerable: true,
  64612. configurable: true
  64613. });
  64614. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  64615. this._renderEffects[renderEffect._name] = renderEffect;
  64616. };
  64617. // private
  64618. PostProcessRenderPipeline.prototype._rebuild = function () {
  64619. };
  64620. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  64621. var renderEffects = this._renderEffects[renderEffectName];
  64622. if (!renderEffects) {
  64623. return;
  64624. }
  64625. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64626. };
  64627. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  64628. var renderEffects = this._renderEffects[renderEffectName];
  64629. if (!renderEffects) {
  64630. return;
  64631. }
  64632. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64633. };
  64634. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  64635. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64636. if (!cams) {
  64637. return;
  64638. }
  64639. var indicesToDelete = [];
  64640. var i;
  64641. for (i = 0; i < cams.length; i++) {
  64642. var camera = cams[i];
  64643. var cameraName = camera.name;
  64644. if (this._cameras.indexOf(camera) === -1) {
  64645. this._cameras[cameraName] = camera;
  64646. }
  64647. else if (unique) {
  64648. indicesToDelete.push(i);
  64649. }
  64650. }
  64651. for (i = 0; i < indicesToDelete.length; i++) {
  64652. cameras.splice(indicesToDelete[i], 1);
  64653. }
  64654. for (var renderEffectName in this._renderEffects) {
  64655. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64656. this._renderEffects[renderEffectName]._attachCameras(cams);
  64657. }
  64658. }
  64659. };
  64660. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  64661. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64662. if (!cams) {
  64663. return;
  64664. }
  64665. for (var renderEffectName in this._renderEffects) {
  64666. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64667. this._renderEffects[renderEffectName]._detachCameras(cams);
  64668. }
  64669. }
  64670. for (var i = 0; i < cams.length; i++) {
  64671. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  64672. }
  64673. };
  64674. PostProcessRenderPipeline.prototype._update = function () {
  64675. for (var renderEffectName in this._renderEffects) {
  64676. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64677. this._renderEffects[renderEffectName]._update();
  64678. }
  64679. }
  64680. for (var i = 0; i < this._cameras.length; i++) {
  64681. var cameraName = this._cameras[i].name;
  64682. if (this._renderEffectsForIsolatedPass[cameraName]) {
  64683. this._renderEffectsForIsolatedPass[cameraName]._update();
  64684. }
  64685. }
  64686. };
  64687. PostProcessRenderPipeline.prototype._reset = function () {
  64688. this._renderEffects = {};
  64689. this._renderEffectsForIsolatedPass = new Array();
  64690. };
  64691. PostProcessRenderPipeline.prototype.dispose = function () {
  64692. // Must be implemented by children
  64693. };
  64694. __decorate([
  64695. BABYLON.serialize()
  64696. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  64697. return PostProcessRenderPipeline;
  64698. }());
  64699. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  64700. })(BABYLON || (BABYLON = {}));
  64701. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  64702. var BABYLON;
  64703. (function (BABYLON) {
  64704. var DepthRenderer = /** @class */ (function () {
  64705. function DepthRenderer(scene, type) {
  64706. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64707. var _this = this;
  64708. this._scene = scene;
  64709. var engine = scene.getEngine();
  64710. // Render target
  64711. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  64712. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64713. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64714. this._depthMap.refreshRate = 1;
  64715. this._depthMap.renderParticles = false;
  64716. this._depthMap.renderList = null;
  64717. // set default depth value to 1.0 (far away)
  64718. this._depthMap.onClearObservable.add(function (engine) {
  64719. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  64720. });
  64721. // Custom render function
  64722. var renderSubMesh = function (subMesh) {
  64723. var mesh = subMesh.getRenderingMesh();
  64724. var scene = _this._scene;
  64725. var engine = scene.getEngine();
  64726. var material = subMesh.getMaterial();
  64727. if (!material) {
  64728. return;
  64729. }
  64730. // Culling and reverse (right handed system)
  64731. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64732. // Managing instances
  64733. var batch = mesh._getInstancesRenderList(subMesh._id);
  64734. if (batch.mustReturn) {
  64735. return;
  64736. }
  64737. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64738. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  64739. engine.enableEffect(_this._effect);
  64740. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64741. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64742. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  64743. // Alpha test
  64744. if (material && material.needAlphaTesting()) {
  64745. var alphaTexture = material.getAlphaTestTexture();
  64746. if (alphaTexture) {
  64747. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64748. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64749. }
  64750. }
  64751. // Bones
  64752. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64753. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64754. }
  64755. // Draw
  64756. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64757. }
  64758. };
  64759. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64760. var index;
  64761. if (depthOnlySubMeshes.length) {
  64762. engine.setColorWrite(false);
  64763. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64764. renderSubMesh(depthOnlySubMeshes.data[index]);
  64765. }
  64766. engine.setColorWrite(true);
  64767. }
  64768. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64769. renderSubMesh(opaqueSubMeshes.data[index]);
  64770. }
  64771. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64772. renderSubMesh(alphaTestSubMeshes.data[index]);
  64773. }
  64774. };
  64775. }
  64776. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  64777. var material = subMesh.getMaterial();
  64778. if (material.disableDepthWrite) {
  64779. return false;
  64780. }
  64781. var defines = [];
  64782. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64783. var mesh = subMesh.getMesh();
  64784. // Alpha test
  64785. if (material && material.needAlphaTesting()) {
  64786. defines.push("#define ALPHATEST");
  64787. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64788. attribs.push(BABYLON.VertexBuffer.UVKind);
  64789. defines.push("#define UV1");
  64790. }
  64791. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64792. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64793. defines.push("#define UV2");
  64794. }
  64795. }
  64796. // Bones
  64797. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64798. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64799. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64800. if (mesh.numBoneInfluencers > 4) {
  64801. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64802. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64803. }
  64804. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64805. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64806. }
  64807. else {
  64808. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64809. }
  64810. // Instances
  64811. if (useInstances) {
  64812. defines.push("#define INSTANCES");
  64813. attribs.push("world0");
  64814. attribs.push("world1");
  64815. attribs.push("world2");
  64816. attribs.push("world3");
  64817. }
  64818. // Get correct effect
  64819. var join = defines.join("\n");
  64820. if (this._cachedDefines !== join) {
  64821. this._cachedDefines = join;
  64822. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  64823. }
  64824. return this._effect.isReady();
  64825. };
  64826. DepthRenderer.prototype.getDepthMap = function () {
  64827. return this._depthMap;
  64828. };
  64829. // Methods
  64830. DepthRenderer.prototype.dispose = function () {
  64831. this._depthMap.dispose();
  64832. };
  64833. return DepthRenderer;
  64834. }());
  64835. BABYLON.DepthRenderer = DepthRenderer;
  64836. })(BABYLON || (BABYLON = {}));
  64837. //# sourceMappingURL=babylon.depthRenderer.js.map
  64838. var BABYLON;
  64839. (function (BABYLON) {
  64840. var SSAORenderingPipeline = /** @class */ (function (_super) {
  64841. __extends(SSAORenderingPipeline, _super);
  64842. /**
  64843. * @constructor
  64844. * @param {string} name - The rendering pipeline name
  64845. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64846. * @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 }
  64847. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64848. */
  64849. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  64850. var _this = _super.call(this, scene.getEngine(), name) || this;
  64851. // Members
  64852. /**
  64853. * The PassPostProcess id in the pipeline that contains the original scene color
  64854. * @type {string}
  64855. */
  64856. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64857. /**
  64858. * The SSAO PostProcess id in the pipeline
  64859. * @type {string}
  64860. */
  64861. _this.SSAORenderEffect = "SSAORenderEffect";
  64862. /**
  64863. * The horizontal blur PostProcess id in the pipeline
  64864. * @type {string}
  64865. */
  64866. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64867. /**
  64868. * The vertical blur PostProcess id in the pipeline
  64869. * @type {string}
  64870. */
  64871. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64872. /**
  64873. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64874. * @type {string}
  64875. */
  64876. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64877. /**
  64878. * The output strength of the SSAO post-process. Default value is 1.0.
  64879. * @type {number}
  64880. */
  64881. _this.totalStrength = 1.0;
  64882. /**
  64883. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  64884. * @type {number}
  64885. */
  64886. _this.radius = 0.0001;
  64887. /**
  64888. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  64889. * Must not be equal to fallOff and superior to fallOff.
  64890. * Default value is 0.975
  64891. * @type {number}
  64892. */
  64893. _this.area = 0.0075;
  64894. /**
  64895. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  64896. * Must not be equal to area and inferior to area.
  64897. * Default value is 0.0
  64898. * @type {number}
  64899. */
  64900. _this.fallOff = 0.000001;
  64901. /**
  64902. * The base color of the SSAO post-process
  64903. * The final result is "base + ssao" between [0, 1]
  64904. * @type {number}
  64905. */
  64906. _this.base = 0.5;
  64907. _this._firstUpdate = true;
  64908. _this._scene = scene;
  64909. // Set up assets
  64910. _this._createRandomTexture();
  64911. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  64912. var ssaoRatio = ratio.ssaoRatio || ratio;
  64913. var combineRatio = ratio.combineRatio || ratio;
  64914. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  64915. _this._createSSAOPostProcess(ssaoRatio);
  64916. _this._createBlurPostProcess(ssaoRatio);
  64917. _this._createSSAOCombinePostProcess(combineRatio);
  64918. // Set up pipeline
  64919. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  64920. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  64921. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  64922. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  64923. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  64924. // Finish
  64925. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64926. if (cameras)
  64927. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  64928. return _this;
  64929. }
  64930. // Public Methods
  64931. /**
  64932. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  64933. */
  64934. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  64935. if (disableDepthRender === void 0) { disableDepthRender = false; }
  64936. for (var i = 0; i < this._scene.cameras.length; i++) {
  64937. var camera = this._scene.cameras[i];
  64938. this._originalColorPostProcess.dispose(camera);
  64939. this._ssaoPostProcess.dispose(camera);
  64940. this._blurHPostProcess.dispose(camera);
  64941. this._blurVPostProcess.dispose(camera);
  64942. this._ssaoCombinePostProcess.dispose(camera);
  64943. }
  64944. this._randomTexture.dispose();
  64945. if (disableDepthRender)
  64946. this._scene.disableDepthRenderer();
  64947. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  64948. _super.prototype.dispose.call(this);
  64949. };
  64950. // Private Methods
  64951. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  64952. var _this = this;
  64953. var size = 16;
  64954. 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);
  64955. 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);
  64956. this._blurHPostProcess.onActivateObservable.add(function () {
  64957. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  64958. _this._blurHPostProcess.kernel = size * dw;
  64959. });
  64960. this._blurVPostProcess.onActivateObservable.add(function () {
  64961. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  64962. _this._blurVPostProcess.kernel = size * dw;
  64963. });
  64964. };
  64965. SSAORenderingPipeline.prototype._rebuild = function () {
  64966. this._firstUpdate = true;
  64967. _super.prototype._rebuild.call(this);
  64968. };
  64969. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  64970. var _this = this;
  64971. var numSamples = 16;
  64972. var sampleSphere = [
  64973. 0.5381, 0.1856, -0.4319,
  64974. 0.1379, 0.2486, 0.4430,
  64975. 0.3371, 0.5679, -0.0057,
  64976. -0.6999, -0.0451, -0.0019,
  64977. 0.0689, -0.1598, -0.8547,
  64978. 0.0560, 0.0069, -0.1843,
  64979. -0.0146, 0.1402, 0.0762,
  64980. 0.0100, -0.1924, -0.0344,
  64981. -0.3577, -0.5301, -0.4358,
  64982. -0.3169, 0.1063, 0.0158,
  64983. 0.0103, -0.5869, 0.0046,
  64984. -0.0897, -0.4940, 0.3287,
  64985. 0.7119, -0.0154, -0.0918,
  64986. -0.0533, 0.0596, -0.5411,
  64987. 0.0352, -0.0631, 0.5460,
  64988. -0.4776, 0.2847, -0.0271
  64989. ];
  64990. var samplesFactor = 1.0 / numSamples;
  64991. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  64992. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  64993. "area", "fallOff", "base", "range", "viewport"
  64994. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  64995. this._ssaoPostProcess.onApply = function (effect) {
  64996. if (_this._firstUpdate) {
  64997. effect.setArray3("sampleSphere", sampleSphere);
  64998. effect.setFloat("samplesFactor", samplesFactor);
  64999. effect.setFloat("randTextureTiles", 4.0);
  65000. }
  65001. effect.setFloat("totalStrength", _this.totalStrength);
  65002. effect.setFloat("radius", _this.radius);
  65003. effect.setFloat("area", _this.area);
  65004. effect.setFloat("fallOff", _this.fallOff);
  65005. effect.setFloat("base", _this.base);
  65006. effect.setTexture("textureSampler", _this._depthTexture);
  65007. effect.setTexture("randomSampler", _this._randomTexture);
  65008. };
  65009. };
  65010. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65011. var _this = this;
  65012. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65013. this._ssaoCombinePostProcess.onApply = function (effect) {
  65014. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65015. };
  65016. };
  65017. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  65018. var size = 512;
  65019. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65020. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65021. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65022. var context = this._randomTexture.getContext();
  65023. var rand = function (min, max) {
  65024. return Math.random() * (max - min) + min;
  65025. };
  65026. var randVector = BABYLON.Vector3.Zero();
  65027. for (var x = 0; x < size; x++) {
  65028. for (var y = 0; y < size; y++) {
  65029. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  65030. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  65031. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  65032. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65033. context.fillRect(x, y, 1, 1);
  65034. }
  65035. }
  65036. this._randomTexture.update(false);
  65037. };
  65038. __decorate([
  65039. BABYLON.serialize()
  65040. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  65041. __decorate([
  65042. BABYLON.serialize()
  65043. ], SSAORenderingPipeline.prototype, "radius", void 0);
  65044. __decorate([
  65045. BABYLON.serialize()
  65046. ], SSAORenderingPipeline.prototype, "area", void 0);
  65047. __decorate([
  65048. BABYLON.serialize()
  65049. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  65050. __decorate([
  65051. BABYLON.serialize()
  65052. ], SSAORenderingPipeline.prototype, "base", void 0);
  65053. return SSAORenderingPipeline;
  65054. }(BABYLON.PostProcessRenderPipeline));
  65055. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  65056. })(BABYLON || (BABYLON = {}));
  65057. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  65058. var BABYLON;
  65059. (function (BABYLON) {
  65060. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  65061. __extends(SSAO2RenderingPipeline, _super);
  65062. /**
  65063. * @constructor
  65064. * @param {string} name - The rendering pipeline name
  65065. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65066. * @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 }
  65067. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65068. */
  65069. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  65070. var _this = _super.call(this, scene.getEngine(), name) || this;
  65071. // Members
  65072. /**
  65073. * The PassPostProcess id in the pipeline that contains the original scene color
  65074. * @type {string}
  65075. */
  65076. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65077. /**
  65078. * The SSAO PostProcess id in the pipeline
  65079. * @type {string}
  65080. */
  65081. _this.SSAORenderEffect = "SSAORenderEffect";
  65082. /**
  65083. * The horizontal blur PostProcess id in the pipeline
  65084. * @type {string}
  65085. */
  65086. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65087. /**
  65088. * The vertical blur PostProcess id in the pipeline
  65089. * @type {string}
  65090. */
  65091. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65092. /**
  65093. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65094. * @type {string}
  65095. */
  65096. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65097. /**
  65098. * The output strength of the SSAO post-process. Default value is 1.0.
  65099. * @type {number}
  65100. */
  65101. _this.totalStrength = 1.0;
  65102. /**
  65103. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  65104. * @type {number}
  65105. */
  65106. _this.maxZ = 100.0;
  65107. /**
  65108. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  65109. * @type {number}
  65110. */
  65111. _this.minZAspect = 0.2;
  65112. /**
  65113. * Number of samples used for the SSAO calculations. Default value is 8
  65114. * @type {number}
  65115. */
  65116. _this._samples = 8;
  65117. /**
  65118. * Are we using bilateral blur ?
  65119. * @type {boolean}
  65120. */
  65121. _this._expensiveBlur = true;
  65122. /**
  65123. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  65124. * @type {number}
  65125. */
  65126. _this.radius = 2.0;
  65127. /**
  65128. * The base color of the SSAO post-process
  65129. * The final result is "base + ssao" between [0, 1]
  65130. * @type {number}
  65131. */
  65132. _this.base = 0.1;
  65133. _this._firstUpdate = true;
  65134. _this._scene = scene;
  65135. if (!_this.isSupported) {
  65136. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  65137. return _this;
  65138. }
  65139. var ssaoRatio = ratio.ssaoRatio || ratio;
  65140. var blurRatio = ratio.blurRatio || ratio;
  65141. // Set up assets
  65142. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  65143. _this._createRandomTexture();
  65144. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  65145. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  65146. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65147. _this._createSSAOPostProcess(1.0);
  65148. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  65149. _this._createSSAOCombinePostProcess(blurRatio);
  65150. // Set up pipeline
  65151. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65152. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65153. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65154. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65155. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65156. // Finish
  65157. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65158. if (cameras)
  65159. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65160. return _this;
  65161. }
  65162. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  65163. get: function () {
  65164. return this._samples;
  65165. },
  65166. set: function (n) {
  65167. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  65168. this._samples = n;
  65169. this._sampleSphere = this._generateHemisphere();
  65170. this._firstUpdate = true;
  65171. },
  65172. enumerable: true,
  65173. configurable: true
  65174. });
  65175. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  65176. get: function () {
  65177. return this._expensiveBlur;
  65178. },
  65179. set: function (b) {
  65180. 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"]);
  65181. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  65182. this._expensiveBlur = b;
  65183. this._firstUpdate = true;
  65184. },
  65185. enumerable: true,
  65186. configurable: true
  65187. });
  65188. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  65189. /**
  65190. * Support test.
  65191. * @type {boolean}
  65192. */
  65193. get: function () {
  65194. var engine = BABYLON.Engine.LastCreatedEngine;
  65195. if (!engine) {
  65196. return false;
  65197. }
  65198. return engine.getCaps().drawBuffersExtension;
  65199. },
  65200. enumerable: true,
  65201. configurable: true
  65202. });
  65203. // Public Methods
  65204. /**
  65205. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65206. */
  65207. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  65208. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  65209. for (var i = 0; i < this._scene.cameras.length; i++) {
  65210. var camera = this._scene.cameras[i];
  65211. this._originalColorPostProcess.dispose(camera);
  65212. this._ssaoPostProcess.dispose(camera);
  65213. this._blurHPostProcess.dispose(camera);
  65214. this._blurVPostProcess.dispose(camera);
  65215. this._ssaoCombinePostProcess.dispose(camera);
  65216. }
  65217. this._randomTexture.dispose();
  65218. if (disableGeometryBufferRenderer)
  65219. this._scene.disableGeometryBufferRenderer();
  65220. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65221. _super.prototype.dispose.call(this);
  65222. };
  65223. // Private Methods
  65224. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  65225. var _this = this;
  65226. this._samplerOffsets = [];
  65227. var expensive = this.expensiveBlur;
  65228. for (var i = -8; i < 8; i++) {
  65229. this._samplerOffsets.push(i * 2 + 0.5);
  65230. }
  65231. 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");
  65232. this._blurHPostProcess.onApply = function (effect) {
  65233. if (!_this._scene.activeCamera) {
  65234. return;
  65235. }
  65236. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  65237. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65238. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65239. effect.setFloat("radius", _this.radius);
  65240. effect.setTexture("depthSampler", _this._depthTexture);
  65241. if (_this._firstUpdate) {
  65242. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65243. }
  65244. };
  65245. 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");
  65246. this._blurVPostProcess.onApply = function (effect) {
  65247. if (!_this._scene.activeCamera) {
  65248. return;
  65249. }
  65250. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  65251. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65252. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65253. effect.setFloat("radius", _this.radius);
  65254. effect.setTexture("depthSampler", _this._depthTexture);
  65255. if (_this._firstUpdate) {
  65256. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65257. _this._firstUpdate = false;
  65258. }
  65259. };
  65260. };
  65261. SSAO2RenderingPipeline.prototype._rebuild = function () {
  65262. this._firstUpdate = true;
  65263. _super.prototype._rebuild.call(this);
  65264. };
  65265. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  65266. var numSamples = this.samples;
  65267. var result = [];
  65268. var vector, scale;
  65269. var rand = function (min, max) {
  65270. return Math.random() * (max - min) + min;
  65271. };
  65272. var i = 0;
  65273. while (i < numSamples) {
  65274. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  65275. vector.normalize();
  65276. scale = i / numSamples;
  65277. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  65278. vector.scaleInPlace(scale);
  65279. result.push(vector.x, vector.y, vector.z);
  65280. i++;
  65281. }
  65282. return result;
  65283. };
  65284. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65285. var _this = this;
  65286. var numSamples = this.samples;
  65287. this._sampleSphere = this._generateHemisphere();
  65288. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  65289. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65290. "base", "range", "projection", "near", "far", "texelSize",
  65291. "xViewport", "yViewport", "maxZ", "minZAspect"
  65292. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65293. this._ssaoPostProcess.onApply = function (effect) {
  65294. if (_this._firstUpdate) {
  65295. effect.setArray3("sampleSphere", _this._sampleSphere);
  65296. effect.setFloat("randTextureTiles", 4.0);
  65297. }
  65298. if (!_this._scene.activeCamera) {
  65299. return;
  65300. }
  65301. effect.setFloat("samplesFactor", 1 / _this.samples);
  65302. effect.setFloat("totalStrength", _this.totalStrength);
  65303. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  65304. effect.setFloat("radius", _this.radius);
  65305. effect.setFloat("maxZ", _this.maxZ);
  65306. effect.setFloat("minZAspect", _this.minZAspect);
  65307. effect.setFloat("base", _this.base);
  65308. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65309. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65310. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  65311. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  65312. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  65313. effect.setTexture("textureSampler", _this._depthTexture);
  65314. effect.setTexture("normalSampler", _this._normalTexture);
  65315. effect.setTexture("randomSampler", _this._randomTexture);
  65316. };
  65317. };
  65318. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65319. var _this = this;
  65320. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65321. this._ssaoCombinePostProcess.onApply = function (effect) {
  65322. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65323. };
  65324. };
  65325. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  65326. var size = 512;
  65327. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65328. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65329. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65330. var context = this._randomTexture.getContext();
  65331. var rand = function (min, max) {
  65332. return Math.random() * (max - min) + min;
  65333. };
  65334. var randVector = BABYLON.Vector3.Zero();
  65335. for (var x = 0; x < size; x++) {
  65336. for (var y = 0; y < size; y++) {
  65337. randVector.x = rand(0.0, 1.0);
  65338. randVector.y = rand(0.0, 1.0);
  65339. randVector.z = 0.0;
  65340. randVector.normalize();
  65341. randVector.scaleInPlace(255);
  65342. randVector.x = Math.floor(randVector.x);
  65343. randVector.y = Math.floor(randVector.y);
  65344. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65345. context.fillRect(x, y, 1, 1);
  65346. }
  65347. }
  65348. this._randomTexture.update(false);
  65349. };
  65350. __decorate([
  65351. BABYLON.serialize()
  65352. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  65353. __decorate([
  65354. BABYLON.serialize()
  65355. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  65356. __decorate([
  65357. BABYLON.serialize()
  65358. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  65359. __decorate([
  65360. BABYLON.serialize("samples")
  65361. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  65362. __decorate([
  65363. BABYLON.serialize("expensiveBlur")
  65364. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  65365. __decorate([
  65366. BABYLON.serialize()
  65367. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  65368. __decorate([
  65369. BABYLON.serialize()
  65370. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  65371. return SSAO2RenderingPipeline;
  65372. }(BABYLON.PostProcessRenderPipeline));
  65373. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  65374. })(BABYLON || (BABYLON = {}));
  65375. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  65376. // BABYLON.JS Chromatic Aberration GLSL Shader
  65377. // Author: Olivier Guyot
  65378. // Separates very slightly R, G and B colors on the edges of the screen
  65379. // Inspired by Francois Tarlier & Martins Upitis
  65380. var BABYLON;
  65381. (function (BABYLON) {
  65382. var LensRenderingPipeline = /** @class */ (function (_super) {
  65383. __extends(LensRenderingPipeline, _super);
  65384. /**
  65385. * @constructor
  65386. *
  65387. * Effect parameters are as follow:
  65388. * {
  65389. * chromatic_aberration: number; // from 0 to x (1 for realism)
  65390. * edge_blur: number; // from 0 to x (1 for realism)
  65391. * distortion: number; // from 0 to x (1 for realism)
  65392. * grain_amount: number; // from 0 to 1
  65393. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  65394. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  65395. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  65396. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  65397. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  65398. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  65399. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  65400. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  65401. * }
  65402. * Note: if an effect parameter is unset, effect is disabled
  65403. *
  65404. * @param {string} name - The rendering pipeline name
  65405. * @param {object} parameters - An object containing all parameters (see above)
  65406. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65407. * @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)
  65408. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65409. */
  65410. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  65411. if (ratio === void 0) { ratio = 1.0; }
  65412. var _this = _super.call(this, scene.getEngine(), name) || this;
  65413. // Lens effects can be of the following:
  65414. // - chromatic aberration (slight shift of RGB colors)
  65415. // - blur on the edge of the lens
  65416. // - lens distortion
  65417. // - depth-of-field blur & highlights enhancing
  65418. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  65419. // - grain effect (noise or custom texture)
  65420. // Two additional texture samplers are needed:
  65421. // - depth map (for depth-of-field)
  65422. // - grain texture
  65423. /**
  65424. * The chromatic aberration PostProcess id in the pipeline
  65425. * @type {string}
  65426. */
  65427. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  65428. /**
  65429. * The highlights enhancing PostProcess id in the pipeline
  65430. * @type {string}
  65431. */
  65432. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  65433. /**
  65434. * The depth-of-field PostProcess id in the pipeline
  65435. * @type {string}
  65436. */
  65437. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  65438. _this._scene = scene;
  65439. // Fetch texture samplers
  65440. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65441. if (parameters.grain_texture) {
  65442. _this._grainTexture = parameters.grain_texture;
  65443. }
  65444. else {
  65445. _this._createGrainTexture();
  65446. }
  65447. // save parameters
  65448. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  65449. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  65450. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  65451. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  65452. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  65453. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  65454. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  65455. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  65456. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  65457. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  65458. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  65459. // Create effects
  65460. _this._createChromaticAberrationPostProcess(ratio);
  65461. _this._createHighlightsPostProcess(ratio);
  65462. _this._createDepthOfFieldPostProcess(ratio / 4);
  65463. // Set up pipeline
  65464. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  65465. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  65466. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  65467. if (_this._highlightsGain === -1) {
  65468. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  65469. }
  65470. // Finish
  65471. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65472. if (cameras) {
  65473. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65474. }
  65475. return _this;
  65476. }
  65477. // public methods (self explanatory)
  65478. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  65479. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  65480. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  65481. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  65482. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  65483. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  65484. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  65485. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  65486. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  65487. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  65488. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  65489. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  65490. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  65491. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  65492. };
  65493. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  65494. this._highlightsPostProcess.updateEffect();
  65495. };
  65496. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  65497. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  65498. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  65499. this._highlightsGain = amount;
  65500. };
  65501. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  65502. if (this._highlightsGain === -1) {
  65503. this._highlightsGain = 1.0;
  65504. }
  65505. this._highlightsThreshold = amount;
  65506. };
  65507. LensRenderingPipeline.prototype.disableHighlights = function () {
  65508. this._highlightsGain = -1;
  65509. };
  65510. /**
  65511. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  65512. */
  65513. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65514. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65515. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65516. this._chromaticAberrationPostProcess = null;
  65517. this._highlightsPostProcess = null;
  65518. this._depthOfFieldPostProcess = null;
  65519. this._grainTexture.dispose();
  65520. if (disableDepthRender)
  65521. this._scene.disableDepthRenderer();
  65522. };
  65523. // colors shifting and distortion
  65524. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  65525. var _this = this;
  65526. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  65527. [], // samplers
  65528. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65529. this._chromaticAberrationPostProcess.onApply = function (effect) {
  65530. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  65531. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65532. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65533. };
  65534. };
  65535. // highlights enhancing
  65536. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  65537. var _this = this;
  65538. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  65539. [], // samplers
  65540. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  65541. this._highlightsPostProcess.onApply = function (effect) {
  65542. effect.setFloat('gain', _this._highlightsGain);
  65543. effect.setFloat('threshold', _this._highlightsThreshold);
  65544. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  65545. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65546. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65547. };
  65548. };
  65549. // colors shifting and distortion
  65550. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  65551. var _this = this;
  65552. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  65553. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  65554. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  65555. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65556. this._depthOfFieldPostProcess.onApply = function (effect) {
  65557. effect.setTexture("depthSampler", _this._depthTexture);
  65558. effect.setTexture("grainSampler", _this._grainTexture);
  65559. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  65560. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  65561. effect.setFloat('grain_amount', _this._grainAmount);
  65562. effect.setBool('blur_noise', _this._blurNoise);
  65563. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65564. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65565. effect.setFloat('distortion', _this._distortion);
  65566. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  65567. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  65568. effect.setFloat('aperture', _this._dofAperture);
  65569. effect.setFloat('darken', _this._dofDarken);
  65570. effect.setFloat('edge_blur', _this._edgeBlur);
  65571. effect.setBool('highlights', (_this._highlightsGain !== -1));
  65572. if (_this._scene.activeCamera) {
  65573. effect.setFloat('near', _this._scene.activeCamera.minZ);
  65574. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  65575. }
  65576. };
  65577. };
  65578. // creates a black and white random noise texture, 512x512
  65579. LensRenderingPipeline.prototype._createGrainTexture = function () {
  65580. var size = 512;
  65581. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65582. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65583. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65584. var context = this._grainTexture.getContext();
  65585. var rand = function (min, max) {
  65586. return Math.random() * (max - min) + min;
  65587. };
  65588. var value;
  65589. for (var x = 0; x < size; x++) {
  65590. for (var y = 0; y < size; y++) {
  65591. value = Math.floor(rand(0.42, 0.58) * 255);
  65592. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  65593. context.fillRect(x, y, 1, 1);
  65594. }
  65595. }
  65596. this._grainTexture.update(false);
  65597. };
  65598. return LensRenderingPipeline;
  65599. }(BABYLON.PostProcessRenderPipeline));
  65600. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  65601. })(BABYLON || (BABYLON = {}));
  65602. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  65603. var BABYLON;
  65604. (function (BABYLON) {
  65605. var StandardRenderingPipeline = /** @class */ (function (_super) {
  65606. __extends(StandardRenderingPipeline, _super);
  65607. /**
  65608. * @constructor
  65609. * @param {string} name - The rendering pipeline name
  65610. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65611. * @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)
  65612. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  65613. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65614. */
  65615. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  65616. if (originalPostProcess === void 0) { originalPostProcess = null; }
  65617. var _this = _super.call(this, scene.getEngine(), name) || this;
  65618. _this.downSampleX4PostProcess = null;
  65619. _this.brightPassPostProcess = null;
  65620. _this.blurHPostProcesses = [];
  65621. _this.blurVPostProcesses = [];
  65622. _this.textureAdderPostProcess = null;
  65623. _this.volumetricLightPostProcess = null;
  65624. _this.volumetricLightSmoothXPostProcess = null;
  65625. _this.volumetricLightSmoothYPostProcess = null;
  65626. _this.volumetricLightMergePostProces = null;
  65627. _this.volumetricLightFinalPostProcess = null;
  65628. _this.luminancePostProcess = null;
  65629. _this.luminanceDownSamplePostProcesses = [];
  65630. _this.hdrPostProcess = null;
  65631. _this.textureAdderFinalPostProcess = null;
  65632. _this.lensFlareFinalPostProcess = null;
  65633. _this.hdrFinalPostProcess = null;
  65634. _this.lensFlarePostProcess = null;
  65635. _this.lensFlareComposePostProcess = null;
  65636. _this.motionBlurPostProcess = null;
  65637. _this.depthOfFieldPostProcess = null;
  65638. // Values
  65639. _this.brightThreshold = 1.0;
  65640. _this.blurWidth = 512.0;
  65641. _this.horizontalBlur = false;
  65642. _this.exposure = 1.0;
  65643. _this.lensTexture = null;
  65644. _this.volumetricLightCoefficient = 0.2;
  65645. _this.volumetricLightPower = 4.0;
  65646. _this.volumetricLightBlurScale = 64.0;
  65647. _this.sourceLight = null;
  65648. _this.hdrMinimumLuminance = 1.0;
  65649. _this.hdrDecreaseRate = 0.5;
  65650. _this.hdrIncreaseRate = 0.5;
  65651. _this.lensColorTexture = null;
  65652. _this.lensFlareStrength = 20.0;
  65653. _this.lensFlareGhostDispersal = 1.4;
  65654. _this.lensFlareHaloWidth = 0.7;
  65655. _this.lensFlareDistortionStrength = 16.0;
  65656. _this.lensStarTexture = null;
  65657. _this.lensFlareDirtTexture = null;
  65658. _this.depthOfFieldDistance = 10.0;
  65659. _this.depthOfFieldBlurWidth = 64.0;
  65660. _this.motionStrength = 1.0;
  65661. // IAnimatable
  65662. _this.animations = [];
  65663. _this._currentDepthOfFieldSource = null;
  65664. _this._hdrCurrentLuminance = 1.0;
  65665. // Getters and setters
  65666. _this._bloomEnabled = true;
  65667. _this._depthOfFieldEnabled = false;
  65668. _this._vlsEnabled = false;
  65669. _this._lensFlareEnabled = false;
  65670. _this._hdrEnabled = false;
  65671. _this._motionBlurEnabled = false;
  65672. _this._motionBlurSamples = 64.0;
  65673. _this._volumetricLightStepsCount = 50.0;
  65674. _this._cameras = cameras || [];
  65675. // Initialize
  65676. _this._scene = scene;
  65677. _this._basePostProcess = originalPostProcess;
  65678. _this._ratio = ratio;
  65679. // Misc
  65680. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65681. // Finish
  65682. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65683. _this._buildPipeline();
  65684. return _this;
  65685. }
  65686. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  65687. get: function () {
  65688. return this._bloomEnabled;
  65689. },
  65690. set: function (enabled) {
  65691. if (this._bloomEnabled === enabled) {
  65692. return;
  65693. }
  65694. this._bloomEnabled = enabled;
  65695. this._buildPipeline();
  65696. },
  65697. enumerable: true,
  65698. configurable: true
  65699. });
  65700. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  65701. get: function () {
  65702. return this._depthOfFieldEnabled;
  65703. },
  65704. set: function (enabled) {
  65705. if (this._depthOfFieldEnabled === enabled) {
  65706. return;
  65707. }
  65708. this._depthOfFieldEnabled = enabled;
  65709. this._buildPipeline();
  65710. },
  65711. enumerable: true,
  65712. configurable: true
  65713. });
  65714. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  65715. get: function () {
  65716. return this._lensFlareEnabled;
  65717. },
  65718. set: function (enabled) {
  65719. if (this._lensFlareEnabled === enabled) {
  65720. return;
  65721. }
  65722. this._lensFlareEnabled = enabled;
  65723. this._buildPipeline();
  65724. },
  65725. enumerable: true,
  65726. configurable: true
  65727. });
  65728. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  65729. get: function () {
  65730. return this._hdrEnabled;
  65731. },
  65732. set: function (enabled) {
  65733. if (this._hdrEnabled === enabled) {
  65734. return;
  65735. }
  65736. this._hdrEnabled = enabled;
  65737. this._buildPipeline();
  65738. },
  65739. enumerable: true,
  65740. configurable: true
  65741. });
  65742. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  65743. get: function () {
  65744. return this._vlsEnabled;
  65745. },
  65746. set: function (enabled) {
  65747. if (this._vlsEnabled === enabled) {
  65748. return;
  65749. }
  65750. if (enabled) {
  65751. var geometry = this._scene.enableGeometryBufferRenderer();
  65752. if (!geometry) {
  65753. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  65754. return;
  65755. }
  65756. }
  65757. this._vlsEnabled = enabled;
  65758. this._buildPipeline();
  65759. },
  65760. enumerable: true,
  65761. configurable: true
  65762. });
  65763. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  65764. get: function () {
  65765. return this._motionBlurEnabled;
  65766. },
  65767. set: function (enabled) {
  65768. if (this._motionBlurEnabled === enabled) {
  65769. return;
  65770. }
  65771. this._motionBlurEnabled = enabled;
  65772. this._buildPipeline();
  65773. },
  65774. enumerable: true,
  65775. configurable: true
  65776. });
  65777. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  65778. get: function () {
  65779. return this._volumetricLightStepsCount;
  65780. },
  65781. set: function (count) {
  65782. if (this.volumetricLightPostProcess) {
  65783. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  65784. }
  65785. this._volumetricLightStepsCount = count;
  65786. },
  65787. enumerable: true,
  65788. configurable: true
  65789. });
  65790. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  65791. get: function () {
  65792. return this._motionBlurSamples;
  65793. },
  65794. set: function (samples) {
  65795. if (this.motionBlurPostProcess) {
  65796. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  65797. }
  65798. this._motionBlurSamples = samples;
  65799. },
  65800. enumerable: true,
  65801. configurable: true
  65802. });
  65803. StandardRenderingPipeline.prototype._buildPipeline = function () {
  65804. var _this = this;
  65805. var ratio = this._ratio;
  65806. var scene = this._scene;
  65807. this._disposePostProcesses();
  65808. this._reset();
  65809. // Create pass post-process
  65810. if (!this._basePostProcess) {
  65811. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  65812. this.originalPostProcess.onApply = function (effect) {
  65813. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  65814. };
  65815. }
  65816. else {
  65817. this.originalPostProcess = this._basePostProcess;
  65818. }
  65819. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  65820. this._currentDepthOfFieldSource = this.originalPostProcess;
  65821. if (this._vlsEnabled) {
  65822. // Create volumetric light
  65823. this._createVolumetricLightPostProcess(scene, ratio);
  65824. // Create volumetric light final post-process
  65825. 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);
  65826. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  65827. }
  65828. if (this._bloomEnabled) {
  65829. // Create down sample X4 post-process
  65830. this._createDownSampleX4PostProcess(scene, ratio / 2);
  65831. // Create bright pass post-process
  65832. this._createBrightPassPostProcess(scene, ratio / 2);
  65833. // Create gaussian blur post-processes (down sampling blurs)
  65834. this._createBlurPostProcesses(scene, ratio / 4, 1);
  65835. // Create texture adder post-process
  65836. this._createTextureAdderPostProcess(scene, ratio);
  65837. // Create depth-of-field source post-process
  65838. 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);
  65839. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  65840. }
  65841. if (this._lensFlareEnabled) {
  65842. // Create lens flare post-process
  65843. this._createLensFlarePostProcess(scene, ratio);
  65844. // Create depth-of-field source post-process post lens-flare and disable it now
  65845. 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);
  65846. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  65847. }
  65848. if (this._hdrEnabled) {
  65849. // Create luminance
  65850. this._createLuminancePostProcesses(scene, this._floatTextureType);
  65851. // Create HDR
  65852. this._createHdrPostProcess(scene, ratio);
  65853. // Create depth-of-field source post-process post hdr and disable it now
  65854. 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);
  65855. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  65856. }
  65857. if (this._depthOfFieldEnabled) {
  65858. // Create gaussian blur used by depth-of-field
  65859. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  65860. // Create depth-of-field post-process
  65861. this._createDepthOfFieldPostProcess(scene, ratio);
  65862. }
  65863. if (this._motionBlurEnabled) {
  65864. // Create motion blur post-process
  65865. this._createMotionBlurPostProcess(scene, ratio);
  65866. }
  65867. if (this._cameras !== null) {
  65868. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  65869. }
  65870. };
  65871. // Down Sample X4 Post-Processs
  65872. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  65873. var _this = this;
  65874. var downSampleX4Offsets = new Array(32);
  65875. 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);
  65876. this.downSampleX4PostProcess.onApply = function (effect) {
  65877. var id = 0;
  65878. var width = _this.downSampleX4PostProcess.width;
  65879. var height = _this.downSampleX4PostProcess.height;
  65880. for (var i = -2; i < 2; i++) {
  65881. for (var j = -2; j < 2; j++) {
  65882. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  65883. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  65884. id += 2;
  65885. }
  65886. }
  65887. effect.setArray2("dsOffsets", downSampleX4Offsets);
  65888. };
  65889. // Add to pipeline
  65890. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  65891. };
  65892. // Brightpass Post-Process
  65893. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  65894. var _this = this;
  65895. var brightOffsets = new Array(8);
  65896. 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);
  65897. this.brightPassPostProcess.onApply = function (effect) {
  65898. var sU = (1.0 / _this.brightPassPostProcess.width);
  65899. var sV = (1.0 / _this.brightPassPostProcess.height);
  65900. brightOffsets[0] = -0.5 * sU;
  65901. brightOffsets[1] = 0.5 * sV;
  65902. brightOffsets[2] = 0.5 * sU;
  65903. brightOffsets[3] = 0.5 * sV;
  65904. brightOffsets[4] = -0.5 * sU;
  65905. brightOffsets[5] = -0.5 * sV;
  65906. brightOffsets[6] = 0.5 * sU;
  65907. brightOffsets[7] = -0.5 * sV;
  65908. effect.setArray2("dsOffsets", brightOffsets);
  65909. effect.setFloat("brightThreshold", _this.brightThreshold);
  65910. };
  65911. // Add to pipeline
  65912. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  65913. };
  65914. // Create blur H&V post-processes
  65915. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  65916. var _this = this;
  65917. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  65918. var engine = scene.getEngine();
  65919. 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);
  65920. 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);
  65921. blurX.onActivateObservable.add(function () {
  65922. var dw = blurX.width / engine.getRenderWidth();
  65923. blurX.kernel = _this[blurWidthKey] * dw;
  65924. });
  65925. blurY.onActivateObservable.add(function () {
  65926. var dw = blurY.height / engine.getRenderHeight();
  65927. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  65928. });
  65929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  65930. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  65931. this.blurHPostProcesses.push(blurX);
  65932. this.blurVPostProcesses.push(blurY);
  65933. };
  65934. // Create texture adder post-process
  65935. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  65936. var _this = this;
  65937. 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);
  65938. this.textureAdderPostProcess.onApply = function (effect) {
  65939. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  65940. effect.setTexture("lensSampler", _this.lensTexture);
  65941. effect.setFloat("exposure", _this.exposure);
  65942. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  65943. };
  65944. // Add to pipeline
  65945. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  65946. };
  65947. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  65948. var _this = this;
  65949. var geometryRenderer = scene.enableGeometryBufferRenderer();
  65950. geometryRenderer.enablePosition = true;
  65951. var geometry = geometryRenderer.getGBuffer();
  65952. // Base post-process
  65953. 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));
  65954. var depthValues = BABYLON.Vector2.Zero();
  65955. this.volumetricLightPostProcess.onApply = function (effect) {
  65956. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  65957. var generator = _this.sourceLight.getShadowGenerator();
  65958. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  65959. effect.setTexture("positionSampler", geometry.textures[2]);
  65960. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  65961. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  65962. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  65963. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  65964. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  65965. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  65966. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  65967. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  65968. effect.setVector2("depthValues", depthValues);
  65969. }
  65970. };
  65971. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  65972. // Smooth
  65973. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  65974. // Merge
  65975. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  65976. this.volumetricLightMergePostProces.onApply = function (effect) {
  65977. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  65978. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  65979. };
  65980. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  65981. };
  65982. // Create luminance
  65983. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  65984. var _this = this;
  65985. // Create luminance
  65986. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  65987. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  65988. var offsets = [];
  65989. this.luminancePostProcess.onApply = function (effect) {
  65990. var sU = (1.0 / _this.luminancePostProcess.width);
  65991. var sV = (1.0 / _this.luminancePostProcess.height);
  65992. offsets[0] = -0.5 * sU;
  65993. offsets[1] = 0.5 * sV;
  65994. offsets[2] = 0.5 * sU;
  65995. offsets[3] = 0.5 * sV;
  65996. offsets[4] = -0.5 * sU;
  65997. offsets[5] = -0.5 * sV;
  65998. offsets[6] = 0.5 * sU;
  65999. offsets[7] = -0.5 * sV;
  66000. effect.setArray2("lumOffsets", offsets);
  66001. };
  66002. // Add to pipeline
  66003. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  66004. // Create down sample luminance
  66005. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  66006. var size = Math.pow(3, i);
  66007. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  66008. if (i === 0) {
  66009. defines += "#define FINAL_DOWN_SAMPLER";
  66010. }
  66011. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  66012. this.luminanceDownSamplePostProcesses.push(postProcess);
  66013. }
  66014. // Create callbacks and add effects
  66015. var lastLuminance = this.luminancePostProcess;
  66016. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  66017. var downSampleOffsets = new Array(18);
  66018. pp.onApply = function (effect) {
  66019. if (!lastLuminance) {
  66020. return;
  66021. }
  66022. var id = 0;
  66023. for (var x = -1; x < 2; x++) {
  66024. for (var y = -1; y < 2; y++) {
  66025. downSampleOffsets[id] = x / lastLuminance.width;
  66026. downSampleOffsets[id + 1] = y / lastLuminance.height;
  66027. id += 2;
  66028. }
  66029. }
  66030. effect.setArray2("dsOffsets", downSampleOffsets);
  66031. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  66032. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66033. lastLuminance = _this.luminancePostProcess;
  66034. }
  66035. else {
  66036. lastLuminance = pp;
  66037. }
  66038. };
  66039. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66040. pp.onAfterRender = function (effect) {
  66041. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  66042. 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);
  66043. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  66044. };
  66045. }
  66046. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  66047. });
  66048. };
  66049. // Create HDR post-process
  66050. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  66051. var _this = this;
  66052. 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);
  66053. var outputLiminance = 1;
  66054. var time = 0;
  66055. var lastTime = 0;
  66056. this.hdrPostProcess.onApply = function (effect) {
  66057. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  66058. time += scene.getEngine().getDeltaTime();
  66059. if (outputLiminance < 0) {
  66060. outputLiminance = _this._hdrCurrentLuminance;
  66061. }
  66062. else {
  66063. var dt = (lastTime - time) / 1000.0;
  66064. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  66065. outputLiminance += _this.hdrDecreaseRate * dt;
  66066. }
  66067. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  66068. outputLiminance -= _this.hdrIncreaseRate * dt;
  66069. }
  66070. else {
  66071. outputLiminance = _this._hdrCurrentLuminance;
  66072. }
  66073. }
  66074. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  66075. effect.setFloat("averageLuminance", outputLiminance);
  66076. lastTime = time;
  66077. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  66078. };
  66079. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  66080. };
  66081. // Create lens flare post-process
  66082. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  66083. var _this = this;
  66084. 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);
  66085. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  66086. this._createBlurPostProcesses(scene, ratio / 4, 2);
  66087. 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);
  66088. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  66089. var resolution = new BABYLON.Vector2(0, 0);
  66090. // Lens flare
  66091. this.lensFlarePostProcess.onApply = function (effect) {
  66092. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  66093. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  66094. effect.setFloat("strength", _this.lensFlareStrength);
  66095. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  66096. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  66097. // Shift
  66098. resolution.x = _this.lensFlarePostProcess.width;
  66099. resolution.y = _this.lensFlarePostProcess.height;
  66100. effect.setVector2("resolution", resolution);
  66101. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  66102. };
  66103. // Compose
  66104. 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);
  66105. 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);
  66106. this.lensFlareComposePostProcess.onApply = function (effect) {
  66107. if (!_this._scene.activeCamera) {
  66108. return;
  66109. }
  66110. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66111. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  66112. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  66113. // Lens start rotation matrix
  66114. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  66115. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  66116. 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));
  66117. camRot *= 4.0;
  66118. 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);
  66119. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  66120. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  66121. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  66122. };
  66123. };
  66124. // Create depth-of-field post-process
  66125. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  66126. var _this = this;
  66127. 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);
  66128. this.depthOfFieldPostProcess.onApply = function (effect) {
  66129. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66130. effect.setTexture("depthSampler", _this._getDepthTexture());
  66131. effect.setFloat("distance", _this.depthOfFieldDistance);
  66132. };
  66133. // Add to pipeline
  66134. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  66135. };
  66136. // Create motion blur post-process
  66137. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  66138. var _this = this;
  66139. 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);
  66140. var motionScale = 0;
  66141. var prevViewProjection = BABYLON.Matrix.Identity();
  66142. var invViewProjection = BABYLON.Matrix.Identity();
  66143. var viewProjection = BABYLON.Matrix.Identity();
  66144. var screenSize = BABYLON.Vector2.Zero();
  66145. this.motionBlurPostProcess.onApply = function (effect) {
  66146. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  66147. viewProjection.invertToRef(invViewProjection);
  66148. effect.setMatrix("inverseViewProjection", invViewProjection);
  66149. effect.setMatrix("prevViewProjection", prevViewProjection);
  66150. prevViewProjection = viewProjection;
  66151. screenSize.x = _this.motionBlurPostProcess.width;
  66152. screenSize.y = _this.motionBlurPostProcess.height;
  66153. effect.setVector2("screenSize", screenSize);
  66154. motionScale = scene.getEngine().getFps() / 60.0;
  66155. effect.setFloat("motionScale", motionScale);
  66156. effect.setFloat("motionStrength", _this.motionStrength);
  66157. effect.setTexture("depthSampler", _this._getDepthTexture());
  66158. };
  66159. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  66160. };
  66161. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  66162. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  66163. var renderer = this._scene.enableGeometryBufferRenderer();
  66164. return renderer.getGBuffer().textures[0];
  66165. }
  66166. return this._scene.enableDepthRenderer().getDepthMap();
  66167. };
  66168. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  66169. for (var i = 0; i < this._cameras.length; i++) {
  66170. var camera = this._cameras[i];
  66171. if (this.originalPostProcess) {
  66172. this.originalPostProcess.dispose(camera);
  66173. }
  66174. if (this.downSampleX4PostProcess) {
  66175. this.downSampleX4PostProcess.dispose(camera);
  66176. }
  66177. if (this.brightPassPostProcess) {
  66178. this.brightPassPostProcess.dispose(camera);
  66179. }
  66180. if (this.textureAdderPostProcess) {
  66181. this.textureAdderPostProcess.dispose(camera);
  66182. }
  66183. if (this.textureAdderFinalPostProcess) {
  66184. this.textureAdderFinalPostProcess.dispose(camera);
  66185. }
  66186. if (this.volumetricLightPostProcess) {
  66187. this.volumetricLightPostProcess.dispose(camera);
  66188. }
  66189. if (this.volumetricLightSmoothXPostProcess) {
  66190. this.volumetricLightSmoothXPostProcess.dispose(camera);
  66191. }
  66192. if (this.volumetricLightSmoothYPostProcess) {
  66193. this.volumetricLightSmoothYPostProcess.dispose(camera);
  66194. }
  66195. if (this.volumetricLightMergePostProces) {
  66196. this.volumetricLightMergePostProces.dispose(camera);
  66197. }
  66198. if (this.volumetricLightFinalPostProcess) {
  66199. this.volumetricLightFinalPostProcess.dispose(camera);
  66200. }
  66201. if (this.lensFlarePostProcess) {
  66202. this.lensFlarePostProcess.dispose(camera);
  66203. }
  66204. if (this.lensFlareComposePostProcess) {
  66205. this.lensFlareComposePostProcess.dispose(camera);
  66206. }
  66207. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  66208. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  66209. }
  66210. if (this.luminancePostProcess) {
  66211. this.luminancePostProcess.dispose(camera);
  66212. }
  66213. if (this.hdrPostProcess) {
  66214. this.hdrPostProcess.dispose(camera);
  66215. }
  66216. if (this.hdrFinalPostProcess) {
  66217. this.hdrFinalPostProcess.dispose(camera);
  66218. }
  66219. if (this.depthOfFieldPostProcess) {
  66220. this.depthOfFieldPostProcess.dispose(camera);
  66221. }
  66222. if (this.motionBlurPostProcess) {
  66223. this.motionBlurPostProcess.dispose(camera);
  66224. }
  66225. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  66226. this.blurHPostProcesses[j].dispose(camera);
  66227. }
  66228. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  66229. this.blurVPostProcesses[j].dispose(camera);
  66230. }
  66231. }
  66232. this.originalPostProcess = null;
  66233. this.downSampleX4PostProcess = null;
  66234. this.brightPassPostProcess = null;
  66235. this.textureAdderPostProcess = null;
  66236. this.textureAdderFinalPostProcess = null;
  66237. this.volumetricLightPostProcess = null;
  66238. this.volumetricLightSmoothXPostProcess = null;
  66239. this.volumetricLightSmoothYPostProcess = null;
  66240. this.volumetricLightMergePostProces = null;
  66241. this.volumetricLightFinalPostProcess = null;
  66242. this.lensFlarePostProcess = null;
  66243. this.lensFlareComposePostProcess = null;
  66244. this.luminancePostProcess = null;
  66245. this.hdrPostProcess = null;
  66246. this.hdrFinalPostProcess = null;
  66247. this.depthOfFieldPostProcess = null;
  66248. this.motionBlurPostProcess = null;
  66249. this.luminanceDownSamplePostProcesses = [];
  66250. this.blurHPostProcesses = [];
  66251. this.blurVPostProcesses = [];
  66252. };
  66253. // Dispose
  66254. StandardRenderingPipeline.prototype.dispose = function () {
  66255. this._disposePostProcesses();
  66256. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66257. _super.prototype.dispose.call(this);
  66258. };
  66259. // Serialize rendering pipeline
  66260. StandardRenderingPipeline.prototype.serialize = function () {
  66261. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66262. serializationObject.customType = "StandardRenderingPipeline";
  66263. return serializationObject;
  66264. };
  66265. /**
  66266. * Static members
  66267. */
  66268. // Parse serialized pipeline
  66269. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66270. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  66271. };
  66272. // Luminance steps
  66273. StandardRenderingPipeline.LuminanceSteps = 6;
  66274. __decorate([
  66275. BABYLON.serialize()
  66276. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  66277. __decorate([
  66278. BABYLON.serialize()
  66279. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  66280. __decorate([
  66281. BABYLON.serialize()
  66282. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  66283. __decorate([
  66284. BABYLON.serialize()
  66285. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  66286. __decorate([
  66287. BABYLON.serializeAsTexture("lensTexture")
  66288. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  66289. __decorate([
  66290. BABYLON.serialize()
  66291. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  66292. __decorate([
  66293. BABYLON.serialize()
  66294. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  66295. __decorate([
  66296. BABYLON.serialize()
  66297. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  66298. __decorate([
  66299. BABYLON.serialize()
  66300. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  66301. __decorate([
  66302. BABYLON.serialize()
  66303. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  66304. __decorate([
  66305. BABYLON.serialize()
  66306. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  66307. __decorate([
  66308. BABYLON.serializeAsTexture("lensColorTexture")
  66309. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  66310. __decorate([
  66311. BABYLON.serialize()
  66312. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  66313. __decorate([
  66314. BABYLON.serialize()
  66315. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  66316. __decorate([
  66317. BABYLON.serialize()
  66318. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  66319. __decorate([
  66320. BABYLON.serialize()
  66321. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  66322. __decorate([
  66323. BABYLON.serializeAsTexture("lensStarTexture")
  66324. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  66325. __decorate([
  66326. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  66327. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  66328. __decorate([
  66329. BABYLON.serialize()
  66330. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  66331. __decorate([
  66332. BABYLON.serialize()
  66333. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  66334. __decorate([
  66335. BABYLON.serialize()
  66336. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  66337. __decorate([
  66338. BABYLON.serialize()
  66339. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  66340. __decorate([
  66341. BABYLON.serialize()
  66342. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  66343. __decorate([
  66344. BABYLON.serialize()
  66345. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  66346. __decorate([
  66347. BABYLON.serialize()
  66348. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  66349. __decorate([
  66350. BABYLON.serialize()
  66351. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  66352. __decorate([
  66353. BABYLON.serialize()
  66354. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  66355. __decorate([
  66356. BABYLON.serialize()
  66357. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  66358. __decorate([
  66359. BABYLON.serialize()
  66360. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  66361. __decorate([
  66362. BABYLON.serialize()
  66363. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  66364. return StandardRenderingPipeline;
  66365. }(BABYLON.PostProcessRenderPipeline));
  66366. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  66367. })(BABYLON || (BABYLON = {}));
  66368. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  66369. var BABYLON;
  66370. (function (BABYLON) {
  66371. var FxaaPostProcess = /** @class */ (function (_super) {
  66372. __extends(FxaaPostProcess, _super);
  66373. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  66374. if (camera === void 0) { camera = null; }
  66375. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66376. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  66377. _this.onApplyObservable.add(function (effect) {
  66378. var texelSize = _this.texelSize;
  66379. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  66380. });
  66381. return _this;
  66382. }
  66383. return FxaaPostProcess;
  66384. }(BABYLON.PostProcess));
  66385. BABYLON.FxaaPostProcess = FxaaPostProcess;
  66386. })(BABYLON || (BABYLON = {}));
  66387. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  66388. var BABYLON;
  66389. (function (BABYLON) {
  66390. /**
  66391. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  66392. */
  66393. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  66394. __extends(CircleOfConfusionPostProcess, _super);
  66395. /**
  66396. * Creates a new instance of @see CircleOfConfusionPostProcess
  66397. * @param name The name of the effect.
  66398. * @param scene The scene the effect belongs to.
  66399. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  66400. * @param options The required width/height ratio to downsize to before computing the render pass.
  66401. * @param camera The camera to apply the render pass to.
  66402. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66403. * @param engine The engine which the post process will be applied. (default: current engine)
  66404. * @param reusable If the post process can be reused on the same frame. (default: false)
  66405. * @param textureType Type of textures used when performing the post process. (default: 0)
  66406. */
  66407. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  66408. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66409. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  66410. /**
  66411. * 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.
  66412. */
  66413. _this.lensSize = 50;
  66414. /**
  66415. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66416. */
  66417. _this.fStop = 1.4;
  66418. /**
  66419. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66420. */
  66421. _this.focusDistance = 2000;
  66422. /**
  66423. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  66424. */
  66425. _this.focalLength = 50;
  66426. _this.onApplyObservable.add(function (effect) {
  66427. effect.setTexture("depthSampler", depthTexture);
  66428. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  66429. var aperture = _this.lensSize / _this.fStop;
  66430. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  66431. effect.setFloat('focusDistance', _this.focusDistance);
  66432. effect.setFloat('cocPrecalculation', cocPrecalculation);
  66433. if (scene.activeCamera) {
  66434. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  66435. }
  66436. });
  66437. return _this;
  66438. }
  66439. return CircleOfConfusionPostProcess;
  66440. }(BABYLON.PostProcess));
  66441. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  66442. })(BABYLON || (BABYLON = {}));
  66443. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  66444. var BABYLON;
  66445. (function (BABYLON) {
  66446. /**
  66447. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  66448. */
  66449. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  66450. __extends(DepthOfFieldMergePostProcess, _super);
  66451. /**
  66452. * Creates a new instance of @see CircleOfConfusionPostProcess
  66453. * @param name The name of the effect.
  66454. * @param original The non-blurred image to be modified
  66455. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  66456. * @param blurSteps Incrimental bluring post processes.
  66457. * @param options The required width/height ratio to downsize to before computing the render pass.
  66458. * @param camera The camera to apply the render pass to.
  66459. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66460. * @param engine The engine which the post process will be applied. (default: current engine)
  66461. * @param reusable If the post process can be reused on the same frame. (default: false)
  66462. * @param textureType Type of textures used when performing the post process. (default: 0)
  66463. */
  66464. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  66465. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66466. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  66467. _this.onApplyObservable.add(function (effect) {
  66468. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  66469. effect.setTextureFromPostProcess("originalSampler", original);
  66470. blurSteps.forEach(function (step, index) {
  66471. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  66472. });
  66473. });
  66474. return _this;
  66475. }
  66476. return DepthOfFieldMergePostProcess;
  66477. }(BABYLON.PostProcess));
  66478. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  66479. })(BABYLON || (BABYLON = {}));
  66480. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  66481. var BABYLON;
  66482. (function (BABYLON) {
  66483. /**
  66484. * Specifies the level of max blur that should be applied when using the depth of field effect
  66485. */
  66486. var DepthOfFieldEffectBlurLevel;
  66487. (function (DepthOfFieldEffectBlurLevel) {
  66488. /**
  66489. * Subtle blur
  66490. */
  66491. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  66492. /**
  66493. * Medium blur
  66494. */
  66495. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  66496. /**
  66497. * Large blur
  66498. */
  66499. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  66500. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  66501. ;
  66502. /**
  66503. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  66504. */
  66505. var DepthOfFieldEffect = /** @class */ (function (_super) {
  66506. __extends(DepthOfFieldEffect, _super);
  66507. /**
  66508. * Creates a new instance of @see DepthOfFieldEffect
  66509. * @param scene The scene the effect belongs to.
  66510. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  66511. */
  66512. function DepthOfFieldEffect(scene, blurLevel, pipelineTextureType) {
  66513. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  66514. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  66515. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  66516. // Enable and get current depth map
  66517. var depthMap = scene.enableDepthRenderer().getDepthMap();
  66518. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  66519. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66520. // Capture circle of confusion texture
  66521. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66522. _this._depthOfFieldPass.autoClear = false;
  66523. // 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)
  66524. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  66525. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  66526. _this._depthOfFieldBlurY = [];
  66527. _this._depthOfFieldBlurX = [];
  66528. var blurCount = 1;
  66529. var kernelSize = 15;
  66530. switch (blurLevel) {
  66531. case DepthOfFieldEffectBlurLevel.High: {
  66532. blurCount = 3;
  66533. kernelSize = 51;
  66534. break;
  66535. }
  66536. case DepthOfFieldEffectBlurLevel.Medium: {
  66537. blurCount = 2;
  66538. kernelSize = 31;
  66539. break;
  66540. }
  66541. default: {
  66542. kernelSize = 15;
  66543. blurCount = 1;
  66544. break;
  66545. }
  66546. }
  66547. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  66548. for (var i = 0; i < blurCount; i++) {
  66549. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66550. blurY.autoClear = false;
  66551. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66552. blurX.autoClear = false;
  66553. _this._depthOfFieldBlurY.push(blurY);
  66554. _this._depthOfFieldBlurX.push(blurX);
  66555. }
  66556. // Merge blurred images with original image based on circleOfConfusion
  66557. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66558. _this._depthOfFieldMerge.autoClear = false;
  66559. // Set all post processes on the effect.
  66560. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  66561. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  66562. effects.push(_this._depthOfFieldBlurY[i]);
  66563. effects.push(_this._depthOfFieldBlurX[i]);
  66564. }
  66565. effects.push(_this._depthOfFieldMerge);
  66566. return effects;
  66567. }, true) || this;
  66568. return _this;
  66569. }
  66570. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  66571. get: function () {
  66572. return this._circleOfConfusion.focalLength;
  66573. },
  66574. /**
  66575. * The focal the length of the camera used in the effect
  66576. */
  66577. set: function (value) {
  66578. this._circleOfConfusion.focalLength = value;
  66579. },
  66580. enumerable: true,
  66581. configurable: true
  66582. });
  66583. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  66584. get: function () {
  66585. return this._circleOfConfusion.fStop;
  66586. },
  66587. /**
  66588. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66589. */
  66590. set: function (value) {
  66591. this._circleOfConfusion.fStop = value;
  66592. },
  66593. enumerable: true,
  66594. configurable: true
  66595. });
  66596. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  66597. get: function () {
  66598. return this._circleOfConfusion.focusDistance;
  66599. },
  66600. /**
  66601. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66602. */
  66603. set: function (value) {
  66604. this._circleOfConfusion.focusDistance = value;
  66605. },
  66606. enumerable: true,
  66607. configurable: true
  66608. });
  66609. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  66610. get: function () {
  66611. return this._circleOfConfusion.lensSize;
  66612. },
  66613. /**
  66614. * 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.
  66615. */
  66616. set: function (value) {
  66617. this._circleOfConfusion.lensSize = value;
  66618. },
  66619. enumerable: true,
  66620. configurable: true
  66621. });
  66622. /**
  66623. * Disposes each of the internal effects for a given camera.
  66624. * @param camera The camera to dispose the effect on.
  66625. */
  66626. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  66627. this._depthOfFieldPass.dispose(camera);
  66628. this._circleOfConfusion.dispose(camera);
  66629. this._depthOfFieldBlurX.forEach(function (element) {
  66630. element.dispose(camera);
  66631. });
  66632. this._depthOfFieldBlurY.forEach(function (element) {
  66633. element.dispose(camera);
  66634. });
  66635. this._depthOfFieldMerge.dispose(camera);
  66636. };
  66637. return DepthOfFieldEffect;
  66638. }(BABYLON.PostProcessRenderEffect));
  66639. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  66640. })(BABYLON || (BABYLON = {}));
  66641. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  66642. var BABYLON;
  66643. (function (BABYLON) {
  66644. /**
  66645. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  66646. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  66647. */
  66648. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  66649. __extends(DefaultRenderingPipeline, _super);
  66650. /**
  66651. * @constructor
  66652. * @param {string} name - The rendering pipeline name
  66653. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66654. * @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)
  66655. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66656. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  66657. */
  66658. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  66659. if (automaticBuild === void 0) { automaticBuild = true; }
  66660. var _this = _super.call(this, scene.getEngine(), name) || this;
  66661. /**
  66662. * ID of the pass post process used for bloom,
  66663. */
  66664. _this.PassPostProcessId = "PassPostProcessEffect";
  66665. /**
  66666. * ID of the highlight post process used for bloom,
  66667. */
  66668. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  66669. /**
  66670. * ID of the blurX post process used for bloom,
  66671. */
  66672. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  66673. /**
  66674. * ID of the blurY post process used for bloom,
  66675. */
  66676. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  66677. /**
  66678. * ID of the copy back post process used for bloom,
  66679. */
  66680. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  66681. /**
  66682. * ID of the image processing post process;
  66683. */
  66684. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  66685. /**
  66686. * ID of the Fast Approximate Anti-Aliasing post process;
  66687. */
  66688. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  66689. /**
  66690. * ID of the final merge post process;
  66691. */
  66692. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  66693. /**
  66694. * Animations which can be used to tweak settings over a period of time
  66695. */
  66696. _this.animations = [];
  66697. // Values
  66698. _this._bloomEnabled = false;
  66699. _this._depthOfFieldEnabled = false;
  66700. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  66701. _this._fxaaEnabled = false;
  66702. _this._imageProcessingEnabled = true;
  66703. _this._bloomScale = 0.6;
  66704. _this._buildAllowed = true;
  66705. /**
  66706. * Specifies the size of the bloom blur kernel, relative to the final output size
  66707. */
  66708. _this.bloomKernel = 64;
  66709. /**
  66710. * Specifies the weight of the bloom in the final rendering
  66711. */
  66712. _this._bloomWeight = 0.15;
  66713. _this._cameras = cameras || [];
  66714. _this._buildAllowed = automaticBuild;
  66715. // Initialize
  66716. _this._scene = scene;
  66717. var caps = _this._scene.getEngine().getCaps();
  66718. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  66719. // Misc
  66720. if (_this._hdr) {
  66721. if (caps.textureHalfFloatRender) {
  66722. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66723. }
  66724. else if (caps.textureFloatRender) {
  66725. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66726. }
  66727. }
  66728. else {
  66729. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66730. }
  66731. // Attach
  66732. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66733. _this._buildPipeline();
  66734. return _this;
  66735. }
  66736. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  66737. get: function () {
  66738. return this._bloomWeight;
  66739. },
  66740. /**
  66741. * The strength of the bloom.
  66742. */
  66743. set: function (value) {
  66744. if (this._bloomWeight === value) {
  66745. return;
  66746. }
  66747. this._bloomWeight = value;
  66748. if (this._hdr && this.copyBack) {
  66749. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  66750. }
  66751. },
  66752. enumerable: true,
  66753. configurable: true
  66754. });
  66755. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  66756. get: function () {
  66757. return this._bloomScale;
  66758. },
  66759. /**
  66760. * The scale of the bloom, lower value will provide better performance.
  66761. */
  66762. set: function (value) {
  66763. if (this._bloomScale === value) {
  66764. return;
  66765. }
  66766. this._bloomScale = value;
  66767. this._buildPipeline();
  66768. },
  66769. enumerable: true,
  66770. configurable: true
  66771. });
  66772. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  66773. get: function () {
  66774. return this._bloomEnabled;
  66775. },
  66776. /**
  66777. * Enable or disable the bloom from the pipeline
  66778. */
  66779. set: function (enabled) {
  66780. if (this._bloomEnabled === enabled) {
  66781. return;
  66782. }
  66783. this._bloomEnabled = enabled;
  66784. this._buildPipeline();
  66785. },
  66786. enumerable: true,
  66787. configurable: true
  66788. });
  66789. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  66790. /**
  66791. * If the depth of field is enabled.
  66792. */
  66793. get: function () {
  66794. return this._depthOfFieldEnabled;
  66795. },
  66796. set: function (enabled) {
  66797. if (this._depthOfFieldEnabled === enabled) {
  66798. return;
  66799. }
  66800. this._depthOfFieldEnabled = enabled;
  66801. this._buildPipeline();
  66802. },
  66803. enumerable: true,
  66804. configurable: true
  66805. });
  66806. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  66807. /**
  66808. * Blur level of the depth of field effect. (Higher blur will effect performance)
  66809. */
  66810. get: function () {
  66811. return this._depthOfFieldBlurLevel;
  66812. },
  66813. set: function (value) {
  66814. if (this._depthOfFieldBlurLevel === value) {
  66815. return;
  66816. }
  66817. this._depthOfFieldBlurLevel = value;
  66818. this._buildPipeline();
  66819. },
  66820. enumerable: true,
  66821. configurable: true
  66822. });
  66823. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  66824. get: function () {
  66825. return this._fxaaEnabled;
  66826. },
  66827. /**
  66828. * If the anti aliasing is enabled.
  66829. */
  66830. set: function (enabled) {
  66831. if (this._fxaaEnabled === enabled) {
  66832. return;
  66833. }
  66834. this._fxaaEnabled = enabled;
  66835. this._buildPipeline();
  66836. },
  66837. enumerable: true,
  66838. configurable: true
  66839. });
  66840. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  66841. get: function () {
  66842. return this._imageProcessingEnabled;
  66843. },
  66844. /**
  66845. * If image processing is enabled.
  66846. */
  66847. set: function (enabled) {
  66848. if (this._imageProcessingEnabled === enabled) {
  66849. return;
  66850. }
  66851. this._imageProcessingEnabled = enabled;
  66852. this._buildPipeline();
  66853. },
  66854. enumerable: true,
  66855. configurable: true
  66856. });
  66857. /**
  66858. * Force the compilation of the entire pipeline.
  66859. */
  66860. DefaultRenderingPipeline.prototype.prepare = function () {
  66861. var previousState = this._buildAllowed;
  66862. this._buildAllowed = true;
  66863. this._buildPipeline();
  66864. this._buildAllowed = previousState;
  66865. };
  66866. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  66867. var _this = this;
  66868. if (!this._buildAllowed) {
  66869. return;
  66870. }
  66871. var engine = this._scene.getEngine();
  66872. this._disposePostProcesses();
  66873. this._reset();
  66874. if (this.depthOfFieldEnabled) {
  66875. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  66876. this.addEffect(this.depthOfField);
  66877. }
  66878. if (this.bloomEnabled) {
  66879. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66880. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  66881. if (!this._hdr) {
  66882. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66883. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  66884. this.highlights.autoClear = false;
  66885. this.highlights.alwaysForcePOT = true;
  66886. }
  66887. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66888. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  66889. this.blurX.alwaysForcePOT = true;
  66890. this.blurX.autoClear = false;
  66891. this.blurX.onActivateObservable.add(function () {
  66892. var dw = _this.blurX.width / engine.getRenderWidth(true);
  66893. _this.blurX.kernel = _this.bloomKernel * dw;
  66894. });
  66895. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66896. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  66897. this.blurY.alwaysForcePOT = true;
  66898. this.blurY.autoClear = false;
  66899. this.blurY.onActivateObservable.add(function () {
  66900. var dh = _this.blurY.height / engine.getRenderHeight(true);
  66901. _this.blurY.kernel = _this.bloomKernel * dh;
  66902. });
  66903. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66904. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  66905. this.copyBack.alwaysForcePOT = true;
  66906. if (this._hdr) {
  66907. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  66908. var w = this.bloomWeight;
  66909. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  66910. }
  66911. else {
  66912. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  66913. }
  66914. this.copyBack.autoClear = false;
  66915. }
  66916. if (this._imageProcessingEnabled) {
  66917. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66918. if (this._hdr) {
  66919. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  66920. }
  66921. else {
  66922. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  66923. }
  66924. }
  66925. if (this.fxaaEnabled) {
  66926. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66927. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  66928. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66929. }
  66930. else if (this._hdr && this.imageProcessing) {
  66931. this.finalMerge = this.imageProcessing;
  66932. }
  66933. else {
  66934. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66935. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  66936. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66937. }
  66938. if (this.bloomEnabled) {
  66939. if (this._hdr) {
  66940. this.copyBack.shareOutputWith(this.blurX);
  66941. if (this.imageProcessing) {
  66942. this.imageProcessing.shareOutputWith(this.pass);
  66943. this.imageProcessing.autoClear = false;
  66944. }
  66945. else if (this.fxaa) {
  66946. this.fxaa.shareOutputWith(this.pass);
  66947. }
  66948. else {
  66949. this.finalMerge.shareOutputWith(this.pass);
  66950. }
  66951. }
  66952. else {
  66953. if (this.fxaa) {
  66954. this.fxaa.shareOutputWith(this.pass);
  66955. }
  66956. else {
  66957. this.finalMerge.shareOutputWith(this.pass);
  66958. }
  66959. }
  66960. }
  66961. if (this._cameras !== null) {
  66962. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66963. }
  66964. };
  66965. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  66966. for (var i = 0; i < this._cameras.length; i++) {
  66967. var camera = this._cameras[i];
  66968. if (this.pass) {
  66969. this.pass.dispose(camera);
  66970. }
  66971. if (this.highlights) {
  66972. this.highlights.dispose(camera);
  66973. }
  66974. if (this.blurX) {
  66975. this.blurX.dispose(camera);
  66976. }
  66977. if (this.blurY) {
  66978. this.blurY.dispose(camera);
  66979. }
  66980. if (this.copyBack) {
  66981. this.copyBack.dispose(camera);
  66982. }
  66983. if (this.imageProcessing) {
  66984. this.imageProcessing.dispose(camera);
  66985. }
  66986. if (this.fxaa) {
  66987. this.fxaa.dispose(camera);
  66988. }
  66989. if (this.finalMerge) {
  66990. this.finalMerge.dispose(camera);
  66991. }
  66992. if (this.depthOfField) {
  66993. this.depthOfField.disposeEffects(camera);
  66994. }
  66995. }
  66996. this.pass = null;
  66997. this.highlights = null;
  66998. this.blurX = null;
  66999. this.blurY = null;
  67000. this.copyBack = null;
  67001. this.imageProcessing = null;
  67002. this.fxaa = null;
  67003. this.finalMerge = null;
  67004. this.depthOfField = null;
  67005. };
  67006. /**
  67007. * Dispose of the pipeline and stop all post processes
  67008. */
  67009. DefaultRenderingPipeline.prototype.dispose = function () {
  67010. this._disposePostProcesses();
  67011. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67012. _super.prototype.dispose.call(this);
  67013. };
  67014. /**
  67015. * Serialize the rendering pipeline (Used when exporting)
  67016. * @returns the serialized object
  67017. */
  67018. DefaultRenderingPipeline.prototype.serialize = function () {
  67019. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67020. serializationObject.customType = "DefaultRenderingPipeline";
  67021. return serializationObject;
  67022. };
  67023. /**
  67024. * Parse the serialized pipeline
  67025. * @param source Source pipeline.
  67026. * @param scene The scene to load the pipeline to.
  67027. * @param rootUrl The URL of the serialized pipeline.
  67028. * @returns An instantiated pipeline from the serialized object.
  67029. */
  67030. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67031. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  67032. };
  67033. __decorate([
  67034. BABYLON.serialize()
  67035. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  67036. __decorate([
  67037. BABYLON.serialize()
  67038. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  67039. __decorate([
  67040. BABYLON.serialize()
  67041. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  67042. __decorate([
  67043. BABYLON.serialize()
  67044. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  67045. __decorate([
  67046. BABYLON.serialize()
  67047. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  67048. __decorate([
  67049. BABYLON.serialize()
  67050. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  67051. __decorate([
  67052. BABYLON.serialize()
  67053. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  67054. __decorate([
  67055. BABYLON.serialize()
  67056. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  67057. __decorate([
  67058. BABYLON.serialize()
  67059. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  67060. __decorate([
  67061. BABYLON.serialize()
  67062. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  67063. return DefaultRenderingPipeline;
  67064. }(BABYLON.PostProcessRenderPipeline));
  67065. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  67066. })(BABYLON || (BABYLON = {}));
  67067. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  67068. var BABYLON;
  67069. (function (BABYLON) {
  67070. /**
  67071. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  67072. */
  67073. var GeometryBufferRenderer = /** @class */ (function () {
  67074. /**
  67075. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  67076. * @param scene The scene the buffer belongs to
  67077. * @param ratio How big is the buffer related to the main canvas.
  67078. */
  67079. function GeometryBufferRenderer(scene, ratio) {
  67080. if (ratio === void 0) { ratio = 1; }
  67081. this._enablePosition = false;
  67082. this._scene = scene;
  67083. this._ratio = ratio;
  67084. // Render target
  67085. this._createRenderTargets();
  67086. }
  67087. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  67088. /**
  67089. * Set the render list (meshes to be rendered) used in the G buffer.
  67090. */
  67091. set: function (meshes) {
  67092. this._multiRenderTarget.renderList = meshes;
  67093. },
  67094. enumerable: true,
  67095. configurable: true
  67096. });
  67097. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  67098. /**
  67099. * Gets wether or not G buffer are supported by the running hardware.
  67100. * This requires draw buffer supports
  67101. */
  67102. get: function () {
  67103. return this._multiRenderTarget.isSupported;
  67104. },
  67105. enumerable: true,
  67106. configurable: true
  67107. });
  67108. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  67109. /**
  67110. * Gets wether or not position are enabled for the G buffer.
  67111. */
  67112. get: function () {
  67113. return this._enablePosition;
  67114. },
  67115. /**
  67116. * Sets wether or not position are enabled for the G buffer.
  67117. */
  67118. set: function (enable) {
  67119. this._enablePosition = enable;
  67120. this.dispose();
  67121. this._createRenderTargets();
  67122. },
  67123. enumerable: true,
  67124. configurable: true
  67125. });
  67126. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  67127. /**
  67128. * Gets the scene associated with the buffer.
  67129. */
  67130. get: function () {
  67131. return this._scene;
  67132. },
  67133. enumerable: true,
  67134. configurable: true
  67135. });
  67136. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  67137. /**
  67138. * Gets the ratio used by the buffer during its creation.
  67139. * How big is the buffer related to the main canvas.
  67140. */
  67141. get: function () {
  67142. return this._ratio;
  67143. },
  67144. enumerable: true,
  67145. configurable: true
  67146. });
  67147. /**
  67148. * Checks wether everything is ready to render a submesh to the G buffer.
  67149. * @param subMesh the submesh to check readiness for
  67150. * @param useInstances is the mesh drawn using instance or not
  67151. * @returns true if ready otherwise false
  67152. */
  67153. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  67154. var material = subMesh.getMaterial();
  67155. if (material && material.disableDepthWrite) {
  67156. return false;
  67157. }
  67158. var defines = [];
  67159. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  67160. var mesh = subMesh.getMesh();
  67161. // Alpha test
  67162. if (material && material.needAlphaTesting()) {
  67163. defines.push("#define ALPHATEST");
  67164. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67165. attribs.push(BABYLON.VertexBuffer.UVKind);
  67166. defines.push("#define UV1");
  67167. }
  67168. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67169. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67170. defines.push("#define UV2");
  67171. }
  67172. }
  67173. // Buffers
  67174. if (this._enablePosition) {
  67175. defines.push("#define POSITION");
  67176. }
  67177. // Bones
  67178. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67179. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67180. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67181. if (mesh.numBoneInfluencers > 4) {
  67182. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67183. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67184. }
  67185. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67186. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67187. }
  67188. else {
  67189. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67190. }
  67191. // Instances
  67192. if (useInstances) {
  67193. defines.push("#define INSTANCES");
  67194. attribs.push("world0");
  67195. attribs.push("world1");
  67196. attribs.push("world2");
  67197. attribs.push("world3");
  67198. }
  67199. // Get correct effect
  67200. var join = defines.join("\n");
  67201. if (this._cachedDefines !== join) {
  67202. this._cachedDefines = join;
  67203. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  67204. }
  67205. return this._effect.isReady();
  67206. };
  67207. /**
  67208. * Gets the current underlying G Buffer.
  67209. * @returns the buffer
  67210. */
  67211. GeometryBufferRenderer.prototype.getGBuffer = function () {
  67212. return this._multiRenderTarget;
  67213. };
  67214. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  67215. /**
  67216. * Gets the number of samples used to render the buffer (anti aliasing).
  67217. */
  67218. get: function () {
  67219. return this._multiRenderTarget.samples;
  67220. },
  67221. /**
  67222. * Sets the number of samples used to render the buffer (anti aliasing).
  67223. */
  67224. set: function (value) {
  67225. this._multiRenderTarget.samples = value;
  67226. },
  67227. enumerable: true,
  67228. configurable: true
  67229. });
  67230. /**
  67231. * Disposes the renderer and frees up associated resources.
  67232. */
  67233. GeometryBufferRenderer.prototype.dispose = function () {
  67234. this.getGBuffer().dispose();
  67235. };
  67236. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  67237. var _this = this;
  67238. var engine = this._scene.getEngine();
  67239. var count = this._enablePosition ? 3 : 2;
  67240. 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 });
  67241. if (!this.isSupported) {
  67242. return;
  67243. }
  67244. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67245. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67246. this._multiRenderTarget.refreshRate = 1;
  67247. this._multiRenderTarget.renderParticles = false;
  67248. this._multiRenderTarget.renderList = null;
  67249. // set default depth value to 1.0 (far away)
  67250. this._multiRenderTarget.onClearObservable.add(function (engine) {
  67251. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  67252. });
  67253. // Custom render function
  67254. var renderSubMesh = function (subMesh) {
  67255. var mesh = subMesh.getRenderingMesh();
  67256. var scene = _this._scene;
  67257. var engine = scene.getEngine();
  67258. var material = subMesh.getMaterial();
  67259. if (!material) {
  67260. return;
  67261. }
  67262. // Culling
  67263. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67264. // Managing instances
  67265. var batch = mesh._getInstancesRenderList(subMesh._id);
  67266. if (batch.mustReturn) {
  67267. return;
  67268. }
  67269. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67270. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  67271. engine.enableEffect(_this._effect);
  67272. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67273. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67274. _this._effect.setMatrix("view", scene.getViewMatrix());
  67275. // Alpha test
  67276. if (material && material.needAlphaTesting()) {
  67277. var alphaTexture = material.getAlphaTestTexture();
  67278. if (alphaTexture) {
  67279. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67280. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67281. }
  67282. }
  67283. // Bones
  67284. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67285. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67286. }
  67287. // Draw
  67288. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67289. }
  67290. };
  67291. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67292. var index;
  67293. if (depthOnlySubMeshes.length) {
  67294. engine.setColorWrite(false);
  67295. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67296. renderSubMesh(depthOnlySubMeshes.data[index]);
  67297. }
  67298. engine.setColorWrite(true);
  67299. }
  67300. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67301. renderSubMesh(opaqueSubMeshes.data[index]);
  67302. }
  67303. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67304. renderSubMesh(alphaTestSubMeshes.data[index]);
  67305. }
  67306. };
  67307. };
  67308. return GeometryBufferRenderer;
  67309. }());
  67310. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  67311. })(BABYLON || (BABYLON = {}));
  67312. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  67313. var BABYLON;
  67314. (function (BABYLON) {
  67315. var RefractionPostProcess = /** @class */ (function (_super) {
  67316. __extends(RefractionPostProcess, _super);
  67317. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  67318. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  67319. _this.color = color;
  67320. _this.depth = depth;
  67321. _this.colorLevel = colorLevel;
  67322. _this.onActivateObservable.add(function (cam) {
  67323. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  67324. });
  67325. _this.onApplyObservable.add(function (effect) {
  67326. effect.setColor3("baseColor", _this.color);
  67327. effect.setFloat("depth", _this.depth);
  67328. effect.setFloat("colorLevel", _this.colorLevel);
  67329. effect.setTexture("refractionSampler", _this._refRexture);
  67330. });
  67331. return _this;
  67332. }
  67333. // Methods
  67334. RefractionPostProcess.prototype.dispose = function (camera) {
  67335. if (this._refRexture) {
  67336. this._refRexture.dispose();
  67337. }
  67338. _super.prototype.dispose.call(this, camera);
  67339. };
  67340. return RefractionPostProcess;
  67341. }(BABYLON.PostProcess));
  67342. BABYLON.RefractionPostProcess = RefractionPostProcess;
  67343. })(BABYLON || (BABYLON = {}));
  67344. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  67345. var BABYLON;
  67346. (function (BABYLON) {
  67347. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  67348. __extends(BlackAndWhitePostProcess, _super);
  67349. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  67350. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  67351. _this.degree = 1;
  67352. _this.onApplyObservable.add(function (effect) {
  67353. effect.setFloat("degree", _this.degree);
  67354. });
  67355. return _this;
  67356. }
  67357. return BlackAndWhitePostProcess;
  67358. }(BABYLON.PostProcess));
  67359. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  67360. })(BABYLON || (BABYLON = {}));
  67361. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  67362. var BABYLON;
  67363. (function (BABYLON) {
  67364. var ConvolutionPostProcess = /** @class */ (function (_super) {
  67365. __extends(ConvolutionPostProcess, _super);
  67366. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  67367. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  67368. _this.kernel = kernel;
  67369. _this.onApply = function (effect) {
  67370. effect.setFloat2("screenSize", _this.width, _this.height);
  67371. effect.setArray("kernel", _this.kernel);
  67372. };
  67373. return _this;
  67374. }
  67375. // Statics
  67376. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67377. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  67378. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  67379. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  67380. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  67381. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  67382. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  67383. return ConvolutionPostProcess;
  67384. }(BABYLON.PostProcess));
  67385. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  67386. })(BABYLON || (BABYLON = {}));
  67387. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  67388. var BABYLON;
  67389. (function (BABYLON) {
  67390. var FilterPostProcess = /** @class */ (function (_super) {
  67391. __extends(FilterPostProcess, _super);
  67392. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  67393. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  67394. _this.kernelMatrix = kernelMatrix;
  67395. _this.onApply = function (effect) {
  67396. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  67397. };
  67398. return _this;
  67399. }
  67400. return FilterPostProcess;
  67401. }(BABYLON.PostProcess));
  67402. BABYLON.FilterPostProcess = FilterPostProcess;
  67403. })(BABYLON || (BABYLON = {}));
  67404. //# sourceMappingURL=babylon.filterPostProcess.js.map
  67405. var BABYLON;
  67406. (function (BABYLON) {
  67407. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  67408. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  67409. __extends(VolumetricLightScatteringPostProcess, _super);
  67410. /**
  67411. * @constructor
  67412. * @param {string} name - The post-process name
  67413. * @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)
  67414. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  67415. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  67416. * @param {number} samples - The post-process quality, default 100
  67417. * @param {number} samplingMode - The post-process filtering mode
  67418. * @param {BABYLON.Engine} engine - The babylon engine
  67419. * @param {boolean} reusable - If the post-process is reusable
  67420. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  67421. */
  67422. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  67423. if (samples === void 0) { samples = 100; }
  67424. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67425. 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;
  67426. _this._screenCoordinates = BABYLON.Vector2.Zero();
  67427. /**
  67428. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  67429. * @type {Vector3}
  67430. */
  67431. _this.customMeshPosition = BABYLON.Vector3.Zero();
  67432. /**
  67433. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  67434. * @type {boolean}
  67435. */
  67436. _this.useCustomMeshPosition = false;
  67437. /**
  67438. * If the post-process should inverse the light scattering direction
  67439. * @type {boolean}
  67440. */
  67441. _this.invert = true;
  67442. /**
  67443. * Array containing the excluded meshes not rendered in the internal pass
  67444. */
  67445. _this.excludedMeshes = new Array();
  67446. /**
  67447. * Controls the overall intensity of the post-process
  67448. * @type {number}
  67449. */
  67450. _this.exposure = 0.3;
  67451. /**
  67452. * Dissipates each sample's contribution in range [0, 1]
  67453. * @type {number}
  67454. */
  67455. _this.decay = 0.96815;
  67456. /**
  67457. * Controls the overall intensity of each sample
  67458. * @type {number}
  67459. */
  67460. _this.weight = 0.58767;
  67461. /**
  67462. * Controls the density of each sample
  67463. * @type {number}
  67464. */
  67465. _this.density = 0.926;
  67466. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  67467. engine = scene.getEngine();
  67468. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  67469. // Configure mesh
  67470. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  67471. // Configure
  67472. _this._createPass(scene, ratio.passRatio || ratio);
  67473. _this.onActivate = function (camera) {
  67474. if (!_this.isSupported) {
  67475. _this.dispose(camera);
  67476. }
  67477. _this.onActivate = null;
  67478. };
  67479. _this.onApplyObservable.add(function (effect) {
  67480. _this._updateMeshScreenCoordinates(scene);
  67481. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  67482. effect.setFloat("exposure", _this.exposure);
  67483. effect.setFloat("decay", _this.decay);
  67484. effect.setFloat("weight", _this.weight);
  67485. effect.setFloat("density", _this.density);
  67486. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  67487. });
  67488. return _this;
  67489. }
  67490. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  67491. get: function () {
  67492. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67493. return false;
  67494. },
  67495. set: function (useDiffuseColor) {
  67496. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67497. },
  67498. enumerable: true,
  67499. configurable: true
  67500. });
  67501. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  67502. return "VolumetricLightScatteringPostProcess";
  67503. };
  67504. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  67505. var mesh = subMesh.getMesh();
  67506. // Render this.mesh as default
  67507. if (mesh === this.mesh && mesh.material) {
  67508. return mesh.material.isReady(mesh);
  67509. }
  67510. var defines = [];
  67511. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67512. var material = subMesh.getMaterial();
  67513. // Alpha test
  67514. if (material) {
  67515. if (material.needAlphaTesting()) {
  67516. defines.push("#define ALPHATEST");
  67517. }
  67518. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67519. attribs.push(BABYLON.VertexBuffer.UVKind);
  67520. defines.push("#define UV1");
  67521. }
  67522. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67523. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67524. defines.push("#define UV2");
  67525. }
  67526. }
  67527. // Bones
  67528. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67529. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67530. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67531. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67532. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  67533. }
  67534. else {
  67535. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67536. }
  67537. // Instances
  67538. if (useInstances) {
  67539. defines.push("#define INSTANCES");
  67540. attribs.push("world0");
  67541. attribs.push("world1");
  67542. attribs.push("world2");
  67543. attribs.push("world3");
  67544. }
  67545. // Get correct effect
  67546. var join = defines.join("\n");
  67547. if (this._cachedDefines !== join) {
  67548. this._cachedDefines = join;
  67549. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  67550. }
  67551. return this._volumetricLightScatteringPass.isReady();
  67552. };
  67553. /**
  67554. * Sets the new light position for light scattering effect
  67555. * @param {BABYLON.Vector3} The new custom light position
  67556. */
  67557. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  67558. this.customMeshPosition = position;
  67559. };
  67560. /**
  67561. * Returns the light position for light scattering effect
  67562. * @return {BABYLON.Vector3} The custom light position
  67563. */
  67564. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  67565. return this.customMeshPosition;
  67566. };
  67567. /**
  67568. * Disposes the internal assets and detaches the post-process from the camera
  67569. */
  67570. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  67571. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  67572. if (rttIndex !== -1) {
  67573. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  67574. }
  67575. this._volumetricLightScatteringRTT.dispose();
  67576. _super.prototype.dispose.call(this, camera);
  67577. };
  67578. /**
  67579. * Returns the render target texture used by the post-process
  67580. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  67581. */
  67582. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  67583. return this._volumetricLightScatteringRTT;
  67584. };
  67585. // Private methods
  67586. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  67587. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  67588. return true;
  67589. }
  67590. return false;
  67591. };
  67592. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  67593. var _this = this;
  67594. var engine = scene.getEngine();
  67595. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67596. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67597. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67598. this._volumetricLightScatteringRTT.renderList = null;
  67599. this._volumetricLightScatteringRTT.renderParticles = false;
  67600. var camera = this.getCamera();
  67601. if (camera) {
  67602. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67603. }
  67604. else {
  67605. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67606. }
  67607. // Custom render function for submeshes
  67608. var renderSubMesh = function (subMesh) {
  67609. var mesh = subMesh.getRenderingMesh();
  67610. if (_this._meshExcluded(mesh)) {
  67611. return;
  67612. }
  67613. var material = subMesh.getMaterial();
  67614. if (!material) {
  67615. return;
  67616. }
  67617. var scene = mesh.getScene();
  67618. var engine = scene.getEngine();
  67619. // Culling
  67620. engine.setState(material.backFaceCulling);
  67621. // Managing instances
  67622. var batch = mesh._getInstancesRenderList(subMesh._id);
  67623. if (batch.mustReturn) {
  67624. return;
  67625. }
  67626. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67627. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  67628. var effect = _this._volumetricLightScatteringPass;
  67629. if (mesh === _this.mesh) {
  67630. if (subMesh.effect) {
  67631. effect = subMesh.effect;
  67632. }
  67633. else {
  67634. effect = material.getEffect();
  67635. }
  67636. }
  67637. engine.enableEffect(effect);
  67638. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  67639. if (mesh === _this.mesh) {
  67640. material.bind(mesh.getWorldMatrix(), mesh);
  67641. }
  67642. else {
  67643. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  67644. // Alpha test
  67645. if (material && material.needAlphaTesting()) {
  67646. var alphaTexture = material.getAlphaTestTexture();
  67647. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  67648. if (alphaTexture) {
  67649. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67650. }
  67651. }
  67652. // Bones
  67653. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67654. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67655. }
  67656. }
  67657. // Draw
  67658. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  67659. }
  67660. };
  67661. // Render target texture callbacks
  67662. var savedSceneClearColor;
  67663. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  67664. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  67665. savedSceneClearColor = scene.clearColor;
  67666. scene.clearColor = sceneClearColor;
  67667. });
  67668. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  67669. scene.clearColor = savedSceneClearColor;
  67670. });
  67671. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67672. var engine = scene.getEngine();
  67673. var index;
  67674. if (depthOnlySubMeshes.length) {
  67675. engine.setColorWrite(false);
  67676. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67677. renderSubMesh(depthOnlySubMeshes.data[index]);
  67678. }
  67679. engine.setColorWrite(true);
  67680. }
  67681. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67682. renderSubMesh(opaqueSubMeshes.data[index]);
  67683. }
  67684. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67685. renderSubMesh(alphaTestSubMeshes.data[index]);
  67686. }
  67687. if (transparentSubMeshes.length) {
  67688. // Sort sub meshes
  67689. for (index = 0; index < transparentSubMeshes.length; index++) {
  67690. var submesh = transparentSubMeshes.data[index];
  67691. var boundingInfo = submesh.getBoundingInfo();
  67692. if (boundingInfo && scene.activeCamera) {
  67693. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  67694. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  67695. }
  67696. }
  67697. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  67698. sortedArray.sort(function (a, b) {
  67699. // Alpha index first
  67700. if (a._alphaIndex > b._alphaIndex) {
  67701. return 1;
  67702. }
  67703. if (a._alphaIndex < b._alphaIndex) {
  67704. return -1;
  67705. }
  67706. // Then distance to camera
  67707. if (a._distanceToCamera < b._distanceToCamera) {
  67708. return 1;
  67709. }
  67710. if (a._distanceToCamera > b._distanceToCamera) {
  67711. return -1;
  67712. }
  67713. return 0;
  67714. });
  67715. // Render sub meshes
  67716. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67717. for (index = 0; index < sortedArray.length; index++) {
  67718. renderSubMesh(sortedArray[index]);
  67719. }
  67720. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67721. }
  67722. };
  67723. };
  67724. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  67725. var transform = scene.getTransformMatrix();
  67726. var meshPosition;
  67727. if (this.useCustomMeshPosition) {
  67728. meshPosition = this.customMeshPosition;
  67729. }
  67730. else if (this.attachedNode) {
  67731. meshPosition = this.attachedNode.position;
  67732. }
  67733. else {
  67734. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  67735. }
  67736. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  67737. this._screenCoordinates.x = pos.x / this._viewPort.width;
  67738. this._screenCoordinates.y = pos.y / this._viewPort.height;
  67739. if (this.invert)
  67740. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  67741. };
  67742. // Static methods
  67743. /**
  67744. * Creates a default mesh for the Volumeric Light Scattering post-process
  67745. * @param {string} The mesh name
  67746. * @param {BABYLON.Scene} The scene where to create the mesh
  67747. * @return {BABYLON.Mesh} the default mesh
  67748. */
  67749. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  67750. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  67751. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  67752. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  67753. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  67754. mesh.material = material;
  67755. return mesh;
  67756. };
  67757. __decorate([
  67758. BABYLON.serializeAsVector3()
  67759. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  67760. __decorate([
  67761. BABYLON.serialize()
  67762. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  67763. __decorate([
  67764. BABYLON.serialize()
  67765. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  67766. __decorate([
  67767. BABYLON.serializeAsMeshReference()
  67768. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  67769. __decorate([
  67770. BABYLON.serialize()
  67771. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  67772. __decorate([
  67773. BABYLON.serialize()
  67774. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  67775. __decorate([
  67776. BABYLON.serialize()
  67777. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  67778. __decorate([
  67779. BABYLON.serialize()
  67780. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  67781. __decorate([
  67782. BABYLON.serialize()
  67783. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  67784. return VolumetricLightScatteringPostProcess;
  67785. }(BABYLON.PostProcess));
  67786. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  67787. })(BABYLON || (BABYLON = {}));
  67788. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  67789. //
  67790. // This post-process allows the modification of rendered colors by using
  67791. // a 'look-up table' (LUT). This effect is also called Color Grading.
  67792. //
  67793. // The object needs to be provided an url to a texture containing the color
  67794. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  67795. // Use an image editing software to tweak the LUT to match your needs.
  67796. //
  67797. // For an example of a color LUT, see here:
  67798. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  67799. // For explanations on color grading, see here:
  67800. // http://udn.epicgames.com/Three/ColorGrading.html
  67801. //
  67802. var BABYLON;
  67803. (function (BABYLON) {
  67804. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  67805. __extends(ColorCorrectionPostProcess, _super);
  67806. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  67807. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  67808. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67809. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  67810. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67811. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67812. _this.onApply = function (effect) {
  67813. effect.setTexture("colorTable", _this._colorTableTexture);
  67814. };
  67815. return _this;
  67816. }
  67817. return ColorCorrectionPostProcess;
  67818. }(BABYLON.PostProcess));
  67819. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  67820. })(BABYLON || (BABYLON = {}));
  67821. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  67822. var BABYLON;
  67823. (function (BABYLON) {
  67824. var TonemappingOperator;
  67825. (function (TonemappingOperator) {
  67826. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  67827. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  67828. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  67829. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  67830. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  67831. ;
  67832. var TonemapPostProcess = /** @class */ (function (_super) {
  67833. __extends(TonemapPostProcess, _super);
  67834. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  67835. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67836. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67837. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  67838. _this._operator = _operator;
  67839. _this.exposureAdjustment = exposureAdjustment;
  67840. var defines = "#define ";
  67841. if (_this._operator === TonemappingOperator.Hable)
  67842. defines += "HABLE_TONEMAPPING";
  67843. else if (_this._operator === TonemappingOperator.Reinhard)
  67844. defines += "REINHARD_TONEMAPPING";
  67845. else if (_this._operator === TonemappingOperator.HejiDawson)
  67846. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  67847. else if (_this._operator === TonemappingOperator.Photographic)
  67848. defines += "PHOTOGRAPHIC_TONEMAPPING";
  67849. //sadly a second call to create the effect.
  67850. _this.updateEffect(defines);
  67851. _this.onApply = function (effect) {
  67852. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  67853. };
  67854. return _this;
  67855. }
  67856. return TonemapPostProcess;
  67857. }(BABYLON.PostProcess));
  67858. BABYLON.TonemapPostProcess = TonemapPostProcess;
  67859. })(BABYLON || (BABYLON = {}));
  67860. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  67861. var BABYLON;
  67862. (function (BABYLON) {
  67863. var DisplayPassPostProcess = /** @class */ (function (_super) {
  67864. __extends(DisplayPassPostProcess, _super);
  67865. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  67866. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  67867. }
  67868. return DisplayPassPostProcess;
  67869. }(BABYLON.PostProcess));
  67870. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  67871. })(BABYLON || (BABYLON = {}));
  67872. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  67873. var BABYLON;
  67874. (function (BABYLON) {
  67875. var HighlightsPostProcess = /** @class */ (function (_super) {
  67876. __extends(HighlightsPostProcess, _super);
  67877. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67878. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67879. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67880. }
  67881. return HighlightsPostProcess;
  67882. }(BABYLON.PostProcess));
  67883. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  67884. })(BABYLON || (BABYLON = {}));
  67885. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  67886. var BABYLON;
  67887. (function (BABYLON) {
  67888. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  67889. __extends(ImageProcessingPostProcess, _super);
  67890. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  67891. if (camera === void 0) { camera = null; }
  67892. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67893. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  67894. _this._fromLinearSpace = true;
  67895. /**
  67896. * Defines cache preventing GC.
  67897. */
  67898. _this._defines = {
  67899. IMAGEPROCESSING: false,
  67900. VIGNETTE: false,
  67901. VIGNETTEBLENDMODEMULTIPLY: false,
  67902. VIGNETTEBLENDMODEOPAQUE: false,
  67903. TONEMAPPING: false,
  67904. CONTRAST: false,
  67905. COLORCURVES: false,
  67906. COLORGRADING: false,
  67907. COLORGRADING3D: false,
  67908. FROMLINEARSPACE: false,
  67909. SAMPLER3DGREENDEPTH: false,
  67910. SAMPLER3DBGRMAP: false,
  67911. IMAGEPROCESSINGPOSTPROCESS: false,
  67912. EXPOSURE: false,
  67913. };
  67914. // Setup the configuration as forced by the constructor. This would then not force the
  67915. // scene materials output in linear space and let untouched the default forward pass.
  67916. if (imageProcessingConfiguration) {
  67917. imageProcessingConfiguration.applyByPostProcess = true;
  67918. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  67919. // This will cause the shader to be compiled
  67920. _this.fromLinearSpace = false;
  67921. }
  67922. else {
  67923. _this._attachImageProcessingConfiguration(null, true);
  67924. _this.imageProcessingConfiguration.applyByPostProcess = true;
  67925. }
  67926. _this.onApply = function (effect) {
  67927. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  67928. };
  67929. return _this;
  67930. }
  67931. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  67932. /**
  67933. * Gets the image processing configuration used either in this material.
  67934. */
  67935. get: function () {
  67936. return this._imageProcessingConfiguration;
  67937. },
  67938. /**
  67939. * Sets the Default image processing configuration used either in the this material.
  67940. *
  67941. * If sets to null, the scene one is in use.
  67942. */
  67943. set: function (value) {
  67944. this._attachImageProcessingConfiguration(value);
  67945. },
  67946. enumerable: true,
  67947. configurable: true
  67948. });
  67949. /**
  67950. * Attaches a new image processing configuration to the PBR Material.
  67951. * @param configuration
  67952. */
  67953. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  67954. var _this = this;
  67955. if (doNotBuild === void 0) { doNotBuild = false; }
  67956. if (configuration === this._imageProcessingConfiguration) {
  67957. return;
  67958. }
  67959. // Detaches observer.
  67960. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  67961. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  67962. }
  67963. // Pick the scene configuration if needed.
  67964. if (!configuration) {
  67965. var scene = null;
  67966. var engine = this.getEngine();
  67967. var camera = this.getCamera();
  67968. if (camera) {
  67969. scene = camera.getScene();
  67970. }
  67971. else if (engine && engine.scenes) {
  67972. var scenes = engine.scenes;
  67973. scene = scenes[scenes.length - 1];
  67974. }
  67975. else {
  67976. scene = BABYLON.Engine.LastCreatedScene;
  67977. }
  67978. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  67979. }
  67980. else {
  67981. this._imageProcessingConfiguration = configuration;
  67982. }
  67983. // Attaches observer.
  67984. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  67985. _this._updateParameters();
  67986. });
  67987. // Ensure the effect will be rebuilt.
  67988. if (!doNotBuild) {
  67989. this._updateParameters();
  67990. }
  67991. };
  67992. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  67993. /**
  67994. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  67995. */
  67996. get: function () {
  67997. return this.imageProcessingConfiguration.colorCurves;
  67998. },
  67999. /**
  68000. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  68001. */
  68002. set: function (value) {
  68003. this.imageProcessingConfiguration.colorCurves = value;
  68004. },
  68005. enumerable: true,
  68006. configurable: true
  68007. });
  68008. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  68009. /**
  68010. * Gets wether the color curves effect is enabled.
  68011. */
  68012. get: function () {
  68013. return this.imageProcessingConfiguration.colorCurvesEnabled;
  68014. },
  68015. /**
  68016. * Sets wether the color curves effect is enabled.
  68017. */
  68018. set: function (value) {
  68019. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  68020. },
  68021. enumerable: true,
  68022. configurable: true
  68023. });
  68024. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  68025. /**
  68026. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68027. */
  68028. get: function () {
  68029. return this.imageProcessingConfiguration.colorGradingTexture;
  68030. },
  68031. /**
  68032. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68033. */
  68034. set: function (value) {
  68035. this.imageProcessingConfiguration.colorGradingTexture = value;
  68036. },
  68037. enumerable: true,
  68038. configurable: true
  68039. });
  68040. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  68041. /**
  68042. * Gets wether the color grading effect is enabled.
  68043. */
  68044. get: function () {
  68045. return this.imageProcessingConfiguration.colorGradingEnabled;
  68046. },
  68047. /**
  68048. * Gets wether the color grading effect is enabled.
  68049. */
  68050. set: function (value) {
  68051. this.imageProcessingConfiguration.colorGradingEnabled = value;
  68052. },
  68053. enumerable: true,
  68054. configurable: true
  68055. });
  68056. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  68057. /**
  68058. * Gets exposure used in the effect.
  68059. */
  68060. get: function () {
  68061. return this.imageProcessingConfiguration.exposure;
  68062. },
  68063. /**
  68064. * Sets exposure used in the effect.
  68065. */
  68066. set: function (value) {
  68067. this.imageProcessingConfiguration.exposure = value;
  68068. },
  68069. enumerable: true,
  68070. configurable: true
  68071. });
  68072. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  68073. /**
  68074. * Gets wether tonemapping is enabled or not.
  68075. */
  68076. get: function () {
  68077. return this._imageProcessingConfiguration.toneMappingEnabled;
  68078. },
  68079. /**
  68080. * Sets wether tonemapping is enabled or not
  68081. */
  68082. set: function (value) {
  68083. this._imageProcessingConfiguration.toneMappingEnabled = value;
  68084. },
  68085. enumerable: true,
  68086. configurable: true
  68087. });
  68088. ;
  68089. ;
  68090. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  68091. /**
  68092. * Gets contrast used in the effect.
  68093. */
  68094. get: function () {
  68095. return this.imageProcessingConfiguration.contrast;
  68096. },
  68097. /**
  68098. * Sets contrast used in the effect.
  68099. */
  68100. set: function (value) {
  68101. this.imageProcessingConfiguration.contrast = value;
  68102. },
  68103. enumerable: true,
  68104. configurable: true
  68105. });
  68106. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  68107. /**
  68108. * Gets Vignette stretch size.
  68109. */
  68110. get: function () {
  68111. return this.imageProcessingConfiguration.vignetteStretch;
  68112. },
  68113. /**
  68114. * Sets Vignette stretch size.
  68115. */
  68116. set: function (value) {
  68117. this.imageProcessingConfiguration.vignetteStretch = value;
  68118. },
  68119. enumerable: true,
  68120. configurable: true
  68121. });
  68122. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  68123. /**
  68124. * Gets Vignette centre X Offset.
  68125. */
  68126. get: function () {
  68127. return this.imageProcessingConfiguration.vignetteCentreX;
  68128. },
  68129. /**
  68130. * Sets Vignette centre X Offset.
  68131. */
  68132. set: function (value) {
  68133. this.imageProcessingConfiguration.vignetteCentreX = value;
  68134. },
  68135. enumerable: true,
  68136. configurable: true
  68137. });
  68138. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  68139. /**
  68140. * Gets Vignette centre Y Offset.
  68141. */
  68142. get: function () {
  68143. return this.imageProcessingConfiguration.vignetteCentreY;
  68144. },
  68145. /**
  68146. * Sets Vignette centre Y Offset.
  68147. */
  68148. set: function (value) {
  68149. this.imageProcessingConfiguration.vignetteCentreY = value;
  68150. },
  68151. enumerable: true,
  68152. configurable: true
  68153. });
  68154. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  68155. /**
  68156. * Gets Vignette weight or intensity of the vignette effect.
  68157. */
  68158. get: function () {
  68159. return this.imageProcessingConfiguration.vignetteWeight;
  68160. },
  68161. /**
  68162. * Sets Vignette weight or intensity of the vignette effect.
  68163. */
  68164. set: function (value) {
  68165. this.imageProcessingConfiguration.vignetteWeight = value;
  68166. },
  68167. enumerable: true,
  68168. configurable: true
  68169. });
  68170. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  68171. /**
  68172. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68173. * if vignetteEnabled is set to true.
  68174. */
  68175. get: function () {
  68176. return this.imageProcessingConfiguration.vignetteColor;
  68177. },
  68178. /**
  68179. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68180. * if vignetteEnabled is set to true.
  68181. */
  68182. set: function (value) {
  68183. this.imageProcessingConfiguration.vignetteColor = value;
  68184. },
  68185. enumerable: true,
  68186. configurable: true
  68187. });
  68188. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  68189. /**
  68190. * Gets Camera field of view used by the Vignette effect.
  68191. */
  68192. get: function () {
  68193. return this.imageProcessingConfiguration.vignetteCameraFov;
  68194. },
  68195. /**
  68196. * Sets Camera field of view used by the Vignette effect.
  68197. */
  68198. set: function (value) {
  68199. this.imageProcessingConfiguration.vignetteCameraFov = value;
  68200. },
  68201. enumerable: true,
  68202. configurable: true
  68203. });
  68204. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  68205. /**
  68206. * Gets the vignette blend mode allowing different kind of effect.
  68207. */
  68208. get: function () {
  68209. return this.imageProcessingConfiguration.vignetteBlendMode;
  68210. },
  68211. /**
  68212. * Sets the vignette blend mode allowing different kind of effect.
  68213. */
  68214. set: function (value) {
  68215. this.imageProcessingConfiguration.vignetteBlendMode = value;
  68216. },
  68217. enumerable: true,
  68218. configurable: true
  68219. });
  68220. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  68221. /**
  68222. * Gets wether the vignette effect is enabled.
  68223. */
  68224. get: function () {
  68225. return this.imageProcessingConfiguration.vignetteEnabled;
  68226. },
  68227. /**
  68228. * Sets wether the vignette effect is enabled.
  68229. */
  68230. set: function (value) {
  68231. this.imageProcessingConfiguration.vignetteEnabled = value;
  68232. },
  68233. enumerable: true,
  68234. configurable: true
  68235. });
  68236. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  68237. /**
  68238. * Gets wether the input of the processing is in Gamma or Linear Space.
  68239. */
  68240. get: function () {
  68241. return this._fromLinearSpace;
  68242. },
  68243. /**
  68244. * Sets wether the input of the processing is in Gamma or Linear Space.
  68245. */
  68246. set: function (value) {
  68247. if (this._fromLinearSpace === value) {
  68248. return;
  68249. }
  68250. this._fromLinearSpace = value;
  68251. this._updateParameters();
  68252. },
  68253. enumerable: true,
  68254. configurable: true
  68255. });
  68256. ImageProcessingPostProcess.prototype.getClassName = function () {
  68257. return "ImageProcessingPostProcess";
  68258. };
  68259. ImageProcessingPostProcess.prototype._updateParameters = function () {
  68260. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  68261. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  68262. var defines = "";
  68263. for (var define in this._defines) {
  68264. if (this._defines[define]) {
  68265. defines += "#define " + define + ";\r\n";
  68266. }
  68267. }
  68268. var samplers = ["textureSampler"];
  68269. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  68270. var uniforms = ["scale"];
  68271. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  68272. this.updateEffect(defines, uniforms, samplers);
  68273. };
  68274. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  68275. _super.prototype.dispose.call(this, camera);
  68276. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68277. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68278. }
  68279. this.imageProcessingConfiguration.applyByPostProcess = false;
  68280. };
  68281. __decorate([
  68282. BABYLON.serialize()
  68283. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  68284. return ImageProcessingPostProcess;
  68285. }(BABYLON.PostProcess));
  68286. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  68287. })(BABYLON || (BABYLON = {}));
  68288. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  68289. var BABYLON;
  68290. (function (BABYLON) {
  68291. /**
  68292. * The Blur Post Process which blurs an image based on a kernel and direction.
  68293. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68294. */
  68295. var BlurPostProcess = /** @class */ (function (_super) {
  68296. __extends(BlurPostProcess, _super);
  68297. /**
  68298. * Creates a new instance of @see BlurPostProcess
  68299. * @param name The name of the effect.
  68300. * @param direction The direction in which to blur the image.
  68301. * @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.
  68302. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68303. * @param camera The camera to apply the render pass to.
  68304. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68305. * @param engine The engine which the post process will be applied. (default: current engine)
  68306. * @param reusable If the post process can be reused on the same frame. (default: false)
  68307. * @param textureType Type of textures used when performing the post process. (default: 0)
  68308. */
  68309. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  68310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68311. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68312. if (defines === void 0) { defines = ""; }
  68313. 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;
  68314. _this.direction = direction;
  68315. _this._packedFloat = false;
  68316. _this._staticDefines = "";
  68317. _this._staticDefines = defines;
  68318. _this.onApplyObservable.add(function (effect) {
  68319. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68320. });
  68321. _this.kernel = kernel;
  68322. return _this;
  68323. }
  68324. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68325. /**
  68326. * Gets the length in pixels of the blur sample region
  68327. */
  68328. get: function () {
  68329. return this._idealKernel;
  68330. },
  68331. /**
  68332. * Sets the length in pixels of the blur sample region
  68333. */
  68334. set: function (v) {
  68335. if (this._idealKernel === v) {
  68336. return;
  68337. }
  68338. v = Math.max(v, 1);
  68339. this._idealKernel = v;
  68340. this._kernel = this._nearestBestKernel(v);
  68341. this._updateParameters();
  68342. },
  68343. enumerable: true,
  68344. configurable: true
  68345. });
  68346. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68347. /**
  68348. * Gets wether or not the blur is unpacking/repacking floats
  68349. */
  68350. get: function () {
  68351. return this._packedFloat;
  68352. },
  68353. /**
  68354. * Sets wether or not the blur needs to unpack/repack floats
  68355. */
  68356. set: function (v) {
  68357. if (this._packedFloat === v) {
  68358. return;
  68359. }
  68360. this._packedFloat = v;
  68361. this._updateParameters();
  68362. },
  68363. enumerable: true,
  68364. configurable: true
  68365. });
  68366. BlurPostProcess.prototype._updateParameters = function () {
  68367. // Generate sampling offsets and weights
  68368. var N = this._kernel;
  68369. var centerIndex = (N - 1) / 2;
  68370. // Generate Gaussian sampling weights over kernel
  68371. var offsets = [];
  68372. var weights = [];
  68373. var totalWeight = 0;
  68374. for (var i = 0; i < N; i++) {
  68375. var u = i / (N - 1);
  68376. var w = this._gaussianWeight(u * 2.0 - 1);
  68377. offsets[i] = (i - centerIndex);
  68378. weights[i] = w;
  68379. totalWeight += w;
  68380. }
  68381. // Normalize weights
  68382. for (var i = 0; i < weights.length; i++) {
  68383. weights[i] /= totalWeight;
  68384. }
  68385. // Optimize: combine samples to take advantage of hardware linear sampling
  68386. // Walk from left to center, combining pairs (symmetrically)
  68387. var linearSamplingWeights = [];
  68388. var linearSamplingOffsets = [];
  68389. var linearSamplingMap = [];
  68390. for (var i = 0; i <= centerIndex; i += 2) {
  68391. var j = Math.min(i + 1, Math.floor(centerIndex));
  68392. var singleCenterSample = i === j;
  68393. if (singleCenterSample) {
  68394. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68395. }
  68396. else {
  68397. var sharedCell = j === centerIndex;
  68398. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68399. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68400. if (offsetLinear === 0) {
  68401. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68402. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68403. }
  68404. else {
  68405. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68406. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68407. }
  68408. }
  68409. }
  68410. for (var i = 0; i < linearSamplingMap.length; i++) {
  68411. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68412. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68413. }
  68414. // Replace with optimized
  68415. offsets = linearSamplingOffsets;
  68416. weights = linearSamplingWeights;
  68417. // Generate shaders
  68418. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68419. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68420. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68421. var defines = "";
  68422. defines += this._staticDefines;
  68423. for (var i = 0; i < varyingCount; i++) {
  68424. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68425. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68426. }
  68427. var depCount = 0;
  68428. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68429. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68430. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68431. depCount++;
  68432. }
  68433. if (this.packedFloat) {
  68434. defines += "#define PACKEDFLOAT 1";
  68435. }
  68436. this.updateEffect(defines, null, null, {
  68437. varyingCount: varyingCount,
  68438. depCount: depCount
  68439. });
  68440. };
  68441. /**
  68442. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68443. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68444. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68445. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68446. * The gaps between physical kernels are compensated for in the weighting of the samples
  68447. * @param idealKernel Ideal blur kernel.
  68448. * @return Nearest best kernel.
  68449. */
  68450. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68451. var v = Math.round(idealKernel);
  68452. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68453. var k = _a[_i];
  68454. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68455. return Math.max(k, 3);
  68456. }
  68457. }
  68458. return Math.max(v, 3);
  68459. };
  68460. /**
  68461. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68462. * @param x The point on the Gaussian distribution to sample.
  68463. * @return the value of the Gaussian function at x.
  68464. */
  68465. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68466. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68467. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68468. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68469. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68470. // truncated at around 1.3% of peak strength.
  68471. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68472. var sigma = (1 / 3);
  68473. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68474. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68475. var weight = (1.0 / denominator) * Math.exp(exponent);
  68476. return weight;
  68477. };
  68478. /**
  68479. * Generates a string that can be used as a floating point number in GLSL.
  68480. * @param x Value to print.
  68481. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68482. * @return GLSL float string.
  68483. */
  68484. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68485. if (decimalFigures === void 0) { decimalFigures = 8; }
  68486. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68487. };
  68488. return BlurPostProcess;
  68489. }(BABYLON.PostProcess));
  68490. BABYLON.BlurPostProcess = BlurPostProcess;
  68491. })(BABYLON || (BABYLON = {}));
  68492. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68493. var BABYLON;
  68494. (function (BABYLON) {
  68495. /**
  68496. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  68497. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  68498. * based on samples that have a large difference in distance than the center pixel.
  68499. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68500. */
  68501. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  68502. __extends(DepthOfFieldBlurPostProcess, _super);
  68503. /**
  68504. * Creates a new instance of @see CircleOfConfusionPostProcess
  68505. * @param name The name of the effect.
  68506. * @param scene The scene the effect belongs to.
  68507. * @param direction The direction the blur should be applied.
  68508. * @param kernel The size of the kernel used to blur.
  68509. * @param options The required width/height ratio to downsize to before computing the render pass.
  68510. * @param camera The camera to apply the render pass to.
  68511. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  68512. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  68513. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68514. * @param engine The engine which the post process will be applied. (default: current engine)
  68515. * @param reusable If the post process can be reused on the same frame. (default: false)
  68516. * @param textureType Type of textures used when performing the post process. (default: 0)
  68517. */
  68518. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType) {
  68519. if (imageToBlur === void 0) { imageToBlur = null; }
  68520. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68521. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68522. 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") || this;
  68523. _this.direction = direction;
  68524. _this.onApplyObservable.add(function (effect) {
  68525. if (imageToBlur != null) {
  68526. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  68527. }
  68528. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68529. if (scene.activeCamera) {
  68530. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  68531. }
  68532. });
  68533. return _this;
  68534. }
  68535. return DepthOfFieldBlurPostProcess;
  68536. }(BABYLON.BlurPostProcess));
  68537. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  68538. })(BABYLON || (BABYLON = {}));
  68539. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  68540. var BABYLON;
  68541. (function (BABYLON) {
  68542. var Bone = /** @class */ (function (_super) {
  68543. __extends(Bone, _super);
  68544. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  68545. if (parentBone === void 0) { parentBone = null; }
  68546. if (localMatrix === void 0) { localMatrix = null; }
  68547. if (restPose === void 0) { restPose = null; }
  68548. if (baseMatrix === void 0) { baseMatrix = null; }
  68549. if (index === void 0) { index = null; }
  68550. var _this = _super.call(this, name, skeleton.getScene()) || this;
  68551. _this.name = name;
  68552. _this.children = new Array();
  68553. _this.animations = new Array();
  68554. // Set this value to map this bone to a different index in the transform matrices.
  68555. // Set this value to -1 to exclude the bone from the transform matrices.
  68556. _this._index = null;
  68557. _this._worldTransform = new BABYLON.Matrix();
  68558. _this._absoluteTransform = new BABYLON.Matrix();
  68559. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  68560. _this._scaleMatrix = BABYLON.Matrix.Identity();
  68561. _this._scaleVector = BABYLON.Vector3.One();
  68562. _this._negateScaleChildren = BABYLON.Vector3.One();
  68563. _this._scalingDeterminant = 1;
  68564. _this._skeleton = skeleton;
  68565. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  68566. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  68567. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  68568. _this._index = index;
  68569. skeleton.bones.push(_this);
  68570. _this.setParent(parentBone, false);
  68571. _this._updateDifferenceMatrix();
  68572. return _this;
  68573. }
  68574. Object.defineProperty(Bone.prototype, "_matrix", {
  68575. get: function () {
  68576. return this._localMatrix;
  68577. },
  68578. set: function (val) {
  68579. if (this._localMatrix) {
  68580. this._localMatrix.copyFrom(val);
  68581. }
  68582. else {
  68583. this._localMatrix = val;
  68584. }
  68585. },
  68586. enumerable: true,
  68587. configurable: true
  68588. });
  68589. // Members
  68590. Bone.prototype.getSkeleton = function () {
  68591. return this._skeleton;
  68592. };
  68593. Bone.prototype.getParent = function () {
  68594. return this._parent;
  68595. };
  68596. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  68597. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68598. if (this._parent === parent) {
  68599. return;
  68600. }
  68601. if (this._parent) {
  68602. var index = this._parent.children.indexOf(this);
  68603. if (index !== -1) {
  68604. this._parent.children.splice(index, 1);
  68605. }
  68606. }
  68607. this._parent = parent;
  68608. if (this._parent) {
  68609. this._parent.children.push(this);
  68610. }
  68611. if (updateDifferenceMatrix) {
  68612. this._updateDifferenceMatrix();
  68613. }
  68614. };
  68615. Bone.prototype.getLocalMatrix = function () {
  68616. return this._localMatrix;
  68617. };
  68618. Bone.prototype.getBaseMatrix = function () {
  68619. return this._baseMatrix;
  68620. };
  68621. Bone.prototype.getRestPose = function () {
  68622. return this._restPose;
  68623. };
  68624. Bone.prototype.returnToRest = function () {
  68625. this.updateMatrix(this._restPose.clone());
  68626. };
  68627. Bone.prototype.getWorldMatrix = function () {
  68628. return this._worldTransform;
  68629. };
  68630. Bone.prototype.getInvertedAbsoluteTransform = function () {
  68631. return this._invertedAbsoluteTransform;
  68632. };
  68633. Bone.prototype.getAbsoluteTransform = function () {
  68634. return this._absoluteTransform;
  68635. };
  68636. Object.defineProperty(Bone.prototype, "position", {
  68637. // Properties (matches AbstractMesh properties)
  68638. get: function () {
  68639. return this.getPosition();
  68640. },
  68641. set: function (newPosition) {
  68642. this.setPosition(newPosition);
  68643. },
  68644. enumerable: true,
  68645. configurable: true
  68646. });
  68647. Object.defineProperty(Bone.prototype, "rotation", {
  68648. get: function () {
  68649. return this.getRotation();
  68650. },
  68651. set: function (newRotation) {
  68652. this.setRotation(newRotation);
  68653. },
  68654. enumerable: true,
  68655. configurable: true
  68656. });
  68657. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  68658. get: function () {
  68659. return this.getRotationQuaternion();
  68660. },
  68661. set: function (newRotation) {
  68662. this.setRotationQuaternion(newRotation);
  68663. },
  68664. enumerable: true,
  68665. configurable: true
  68666. });
  68667. Object.defineProperty(Bone.prototype, "scaling", {
  68668. get: function () {
  68669. return this.getScale();
  68670. },
  68671. set: function (newScaling) {
  68672. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  68673. },
  68674. enumerable: true,
  68675. configurable: true
  68676. });
  68677. // Methods
  68678. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  68679. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68680. this._baseMatrix = matrix.clone();
  68681. this._localMatrix = matrix.clone();
  68682. this._skeleton._markAsDirty();
  68683. if (updateDifferenceMatrix) {
  68684. this._updateDifferenceMatrix();
  68685. }
  68686. };
  68687. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  68688. if (!rootMatrix) {
  68689. rootMatrix = this._baseMatrix;
  68690. }
  68691. if (this._parent) {
  68692. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  68693. }
  68694. else {
  68695. this._absoluteTransform.copyFrom(rootMatrix);
  68696. }
  68697. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  68698. for (var index = 0; index < this.children.length; index++) {
  68699. this.children[index]._updateDifferenceMatrix();
  68700. }
  68701. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  68702. };
  68703. Bone.prototype.markAsDirty = function () {
  68704. this._currentRenderId++;
  68705. this._skeleton._markAsDirty();
  68706. };
  68707. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  68708. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  68709. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  68710. // all animation may be coming from a library skeleton, so may need to create animation
  68711. if (this.animations.length === 0) {
  68712. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  68713. this.animations[0].setKeys([]);
  68714. }
  68715. // get animation info / verify there is such a range from the source bone
  68716. var sourceRange = source.animations[0].getRange(rangeName);
  68717. if (!sourceRange) {
  68718. return false;
  68719. }
  68720. var from = sourceRange.from;
  68721. var to = sourceRange.to;
  68722. var sourceKeys = source.animations[0].getKeys();
  68723. // rescaling prep
  68724. var sourceBoneLength = source.length;
  68725. var sourceParent = source.getParent();
  68726. var parent = this.getParent();
  68727. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  68728. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  68729. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  68730. var destKeys = this.animations[0].getKeys();
  68731. // loop vars declaration
  68732. var orig;
  68733. var origTranslation;
  68734. var mat;
  68735. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  68736. orig = sourceKeys[key];
  68737. if (orig.frame >= from && orig.frame <= to) {
  68738. if (rescaleAsRequired) {
  68739. mat = orig.value.clone();
  68740. // scale based on parent ratio, when bone has parent
  68741. if (parentScalingReqd) {
  68742. origTranslation = mat.getTranslation();
  68743. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  68744. // scale based on skeleton dimension ratio when root bone, and value is passed
  68745. }
  68746. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  68747. origTranslation = mat.getTranslation();
  68748. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  68749. // use original when root bone, and no data for skelDimensionsRatio
  68750. }
  68751. else {
  68752. mat = orig.value;
  68753. }
  68754. }
  68755. else {
  68756. mat = orig.value;
  68757. }
  68758. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  68759. }
  68760. }
  68761. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  68762. return true;
  68763. };
  68764. /**
  68765. * Translate the bone in local or world space.
  68766. * @param vec The amount to translate the bone.
  68767. * @param space The space that the translation is in.
  68768. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68769. */
  68770. Bone.prototype.translate = function (vec, space, mesh) {
  68771. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68772. var lm = this.getLocalMatrix();
  68773. if (space == BABYLON.Space.LOCAL) {
  68774. lm.m[12] += vec.x;
  68775. lm.m[13] += vec.y;
  68776. lm.m[14] += vec.z;
  68777. }
  68778. else {
  68779. var wm = null;
  68780. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68781. if (mesh) {
  68782. wm = mesh.getWorldMatrix();
  68783. }
  68784. this._skeleton.computeAbsoluteTransforms();
  68785. var tmat = Bone._tmpMats[0];
  68786. var tvec = Bone._tmpVecs[0];
  68787. if (this._parent) {
  68788. if (mesh && wm) {
  68789. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68790. tmat.multiplyToRef(wm, tmat);
  68791. }
  68792. else {
  68793. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68794. }
  68795. }
  68796. tmat.m[12] = 0;
  68797. tmat.m[13] = 0;
  68798. tmat.m[14] = 0;
  68799. tmat.invert();
  68800. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  68801. lm.m[12] += tvec.x;
  68802. lm.m[13] += tvec.y;
  68803. lm.m[14] += tvec.z;
  68804. }
  68805. this.markAsDirty();
  68806. };
  68807. /**
  68808. * Set the postion of the bone in local or world space.
  68809. * @param position The position to set the bone.
  68810. * @param space The space that the position is in.
  68811. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68812. */
  68813. Bone.prototype.setPosition = function (position, space, mesh) {
  68814. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68815. var lm = this.getLocalMatrix();
  68816. if (space == BABYLON.Space.LOCAL) {
  68817. lm.m[12] = position.x;
  68818. lm.m[13] = position.y;
  68819. lm.m[14] = position.z;
  68820. }
  68821. else {
  68822. var wm = null;
  68823. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68824. if (mesh) {
  68825. wm = mesh.getWorldMatrix();
  68826. }
  68827. this._skeleton.computeAbsoluteTransforms();
  68828. var tmat = Bone._tmpMats[0];
  68829. var vec = Bone._tmpVecs[0];
  68830. if (this._parent) {
  68831. if (mesh && wm) {
  68832. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68833. tmat.multiplyToRef(wm, tmat);
  68834. }
  68835. else {
  68836. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68837. }
  68838. }
  68839. tmat.invert();
  68840. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  68841. lm.m[12] = vec.x;
  68842. lm.m[13] = vec.y;
  68843. lm.m[14] = vec.z;
  68844. }
  68845. this.markAsDirty();
  68846. };
  68847. /**
  68848. * Set the absolute postion of the bone (world space).
  68849. * @param position The position to set the bone.
  68850. * @param mesh The mesh that this bone is attached to.
  68851. */
  68852. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  68853. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  68854. };
  68855. /**
  68856. * Set the scale of the bone on the x, y and z axes.
  68857. * @param x The scale of the bone on the x axis.
  68858. * @param x The scale of the bone on the y axis.
  68859. * @param z The scale of the bone on the z axis.
  68860. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68861. */
  68862. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  68863. if (scaleChildren === void 0) { scaleChildren = false; }
  68864. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  68865. if (!scaleChildren) {
  68866. this._negateScaleChildren.x = 1 / x;
  68867. this._negateScaleChildren.y = 1 / y;
  68868. this._negateScaleChildren.z = 1 / z;
  68869. }
  68870. this._syncScaleVector();
  68871. }
  68872. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  68873. };
  68874. /**
  68875. * Scale the bone on the x, y and z axes.
  68876. * @param x The amount to scale the bone on the x axis.
  68877. * @param x The amount to scale the bone on the y axis.
  68878. * @param z The amount to scale the bone on the z axis.
  68879. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68880. */
  68881. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  68882. if (scaleChildren === void 0) { scaleChildren = false; }
  68883. var locMat = this.getLocalMatrix();
  68884. var origLocMat = Bone._tmpMats[0];
  68885. origLocMat.copyFrom(locMat);
  68886. var origLocMatInv = Bone._tmpMats[1];
  68887. origLocMatInv.copyFrom(origLocMat);
  68888. origLocMatInv.invert();
  68889. var scaleMat = Bone._tmpMats[2];
  68890. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  68891. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  68892. this._scaleVector.x *= x;
  68893. this._scaleVector.y *= y;
  68894. this._scaleVector.z *= z;
  68895. locMat.multiplyToRef(origLocMatInv, locMat);
  68896. locMat.multiplyToRef(scaleMat, locMat);
  68897. locMat.multiplyToRef(origLocMat, locMat);
  68898. var parent = this.getParent();
  68899. if (parent) {
  68900. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  68901. }
  68902. else {
  68903. this.getAbsoluteTransform().copyFrom(locMat);
  68904. }
  68905. var len = this.children.length;
  68906. scaleMat.invert();
  68907. for (var i = 0; i < len; i++) {
  68908. var child = this.children[i];
  68909. var cm = child.getLocalMatrix();
  68910. cm.multiplyToRef(scaleMat, cm);
  68911. var lm = child.getLocalMatrix();
  68912. lm.m[12] *= x;
  68913. lm.m[13] *= y;
  68914. lm.m[14] *= z;
  68915. }
  68916. this.computeAbsoluteTransforms();
  68917. if (scaleChildren) {
  68918. for (var i = 0; i < len; i++) {
  68919. this.children[i].scale(x, y, z, scaleChildren);
  68920. }
  68921. }
  68922. this.markAsDirty();
  68923. };
  68924. /**
  68925. * Set the yaw, pitch, and roll of the bone in local or world space.
  68926. * @param yaw The rotation of the bone on the y axis.
  68927. * @param pitch The rotation of the bone on the x axis.
  68928. * @param roll The rotation of the bone on the z axis.
  68929. * @param space The space that the axes of rotation are in.
  68930. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68931. */
  68932. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  68933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68934. var rotMat = Bone._tmpMats[0];
  68935. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  68936. var rotMatInv = Bone._tmpMats[1];
  68937. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68938. rotMatInv.multiplyToRef(rotMat, rotMat);
  68939. this._rotateWithMatrix(rotMat, space, mesh);
  68940. };
  68941. /**
  68942. * Rotate the bone on an axis in local or world space.
  68943. * @param axis The axis to rotate the bone on.
  68944. * @param amount The amount to rotate the bone.
  68945. * @param space The space that the axis is in.
  68946. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68947. */
  68948. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  68949. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68950. var rmat = Bone._tmpMats[0];
  68951. rmat.m[12] = 0;
  68952. rmat.m[13] = 0;
  68953. rmat.m[14] = 0;
  68954. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  68955. this._rotateWithMatrix(rmat, space, mesh);
  68956. };
  68957. /**
  68958. * Set the rotation of the bone to a particular axis angle in local or world space.
  68959. * @param axis The axis to rotate the bone on.
  68960. * @param angle The angle that the bone should be rotated to.
  68961. * @param space The space that the axis is in.
  68962. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68963. */
  68964. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  68965. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68966. var rotMat = Bone._tmpMats[0];
  68967. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  68968. var rotMatInv = Bone._tmpMats[1];
  68969. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68970. rotMatInv.multiplyToRef(rotMat, rotMat);
  68971. this._rotateWithMatrix(rotMat, space, mesh);
  68972. };
  68973. /**
  68974. * Set the euler rotation of the bone in local of world space.
  68975. * @param rotation The euler rotation that the bone should be set to.
  68976. * @param space The space that the rotation is in.
  68977. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68978. */
  68979. Bone.prototype.setRotation = function (rotation, space, mesh) {
  68980. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68981. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  68982. };
  68983. /**
  68984. * Set the quaternion rotation of the bone in local of world space.
  68985. * @param quat The quaternion rotation that the bone should be set to.
  68986. * @param space The space that the rotation is in.
  68987. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68988. */
  68989. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  68990. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68991. var rotMatInv = Bone._tmpMats[0];
  68992. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68993. var rotMat = Bone._tmpMats[1];
  68994. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  68995. rotMatInv.multiplyToRef(rotMat, rotMat);
  68996. this._rotateWithMatrix(rotMat, space, mesh);
  68997. };
  68998. /**
  68999. * Set the rotation matrix of the bone in local of world space.
  69000. * @param rotMat The rotation matrix that the bone should be set to.
  69001. * @param space The space that the rotation is in.
  69002. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69003. */
  69004. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  69005. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69006. var rotMatInv = Bone._tmpMats[0];
  69007. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69008. var rotMat2 = Bone._tmpMats[1];
  69009. rotMat2.copyFrom(rotMat);
  69010. rotMatInv.multiplyToRef(rotMat, rotMat2);
  69011. this._rotateWithMatrix(rotMat2, space, mesh);
  69012. };
  69013. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  69014. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69015. var lmat = this.getLocalMatrix();
  69016. var lx = lmat.m[12];
  69017. var ly = lmat.m[13];
  69018. var lz = lmat.m[14];
  69019. var parent = this.getParent();
  69020. var parentScale = Bone._tmpMats[3];
  69021. var parentScaleInv = Bone._tmpMats[4];
  69022. if (parent) {
  69023. if (space == BABYLON.Space.WORLD) {
  69024. if (mesh) {
  69025. parentScale.copyFrom(mesh.getWorldMatrix());
  69026. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  69027. }
  69028. else {
  69029. parentScale.copyFrom(parent.getAbsoluteTransform());
  69030. }
  69031. }
  69032. else {
  69033. parentScale = parent._scaleMatrix;
  69034. }
  69035. parentScaleInv.copyFrom(parentScale);
  69036. parentScaleInv.invert();
  69037. lmat.multiplyToRef(parentScale, lmat);
  69038. lmat.multiplyToRef(rmat, lmat);
  69039. lmat.multiplyToRef(parentScaleInv, lmat);
  69040. }
  69041. else {
  69042. if (space == BABYLON.Space.WORLD && mesh) {
  69043. parentScale.copyFrom(mesh.getWorldMatrix());
  69044. parentScaleInv.copyFrom(parentScale);
  69045. parentScaleInv.invert();
  69046. lmat.multiplyToRef(parentScale, lmat);
  69047. lmat.multiplyToRef(rmat, lmat);
  69048. lmat.multiplyToRef(parentScaleInv, lmat);
  69049. }
  69050. else {
  69051. lmat.multiplyToRef(rmat, lmat);
  69052. }
  69053. }
  69054. lmat.m[12] = lx;
  69055. lmat.m[13] = ly;
  69056. lmat.m[14] = lz;
  69057. this.computeAbsoluteTransforms();
  69058. this.markAsDirty();
  69059. };
  69060. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  69061. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69062. if (space == BABYLON.Space.WORLD) {
  69063. var scaleMatrix = Bone._tmpMats[2];
  69064. scaleMatrix.copyFrom(this._scaleMatrix);
  69065. rotMatInv.copyFrom(this.getAbsoluteTransform());
  69066. if (mesh) {
  69067. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  69068. var meshScale = Bone._tmpMats[3];
  69069. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  69070. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  69071. }
  69072. rotMatInv.invert();
  69073. scaleMatrix.m[0] *= this._scalingDeterminant;
  69074. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69075. }
  69076. else {
  69077. rotMatInv.copyFrom(this.getLocalMatrix());
  69078. rotMatInv.invert();
  69079. var scaleMatrix = Bone._tmpMats[2];
  69080. scaleMatrix.copyFrom(this._scaleMatrix);
  69081. if (this._parent) {
  69082. var pscaleMatrix = Bone._tmpMats[3];
  69083. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  69084. pscaleMatrix.invert();
  69085. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  69086. }
  69087. else {
  69088. scaleMatrix.m[0] *= this._scalingDeterminant;
  69089. }
  69090. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69091. }
  69092. };
  69093. /**
  69094. * Get the scale of the bone
  69095. * @returns the scale of the bone
  69096. */
  69097. Bone.prototype.getScale = function () {
  69098. return this._scaleVector.clone();
  69099. };
  69100. /**
  69101. * Copy the scale of the bone to a vector3.
  69102. * @param result The vector3 to copy the scale to
  69103. */
  69104. Bone.prototype.getScaleToRef = function (result) {
  69105. result.copyFrom(this._scaleVector);
  69106. };
  69107. /**
  69108. * Get the position of the bone in local or world space.
  69109. * @param space The space that the returned position is in.
  69110. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69111. * @returns The position of the bone
  69112. */
  69113. Bone.prototype.getPosition = function (space, mesh) {
  69114. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69115. if (mesh === void 0) { mesh = null; }
  69116. var pos = BABYLON.Vector3.Zero();
  69117. this.getPositionToRef(space, mesh, pos);
  69118. return pos;
  69119. };
  69120. /**
  69121. * Copy the position of the bone to a vector3 in local or world space.
  69122. * @param space The space that the returned position is in.
  69123. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69124. * @param result The vector3 to copy the position to.
  69125. */
  69126. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  69127. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69128. if (space == BABYLON.Space.LOCAL) {
  69129. var lm = this.getLocalMatrix();
  69130. result.x = lm.m[12];
  69131. result.y = lm.m[13];
  69132. result.z = lm.m[14];
  69133. }
  69134. else {
  69135. var wm = null;
  69136. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69137. if (mesh) {
  69138. wm = mesh.getWorldMatrix();
  69139. }
  69140. this._skeleton.computeAbsoluteTransforms();
  69141. var tmat = Bone._tmpMats[0];
  69142. if (mesh && wm) {
  69143. tmat.copyFrom(this.getAbsoluteTransform());
  69144. tmat.multiplyToRef(wm, tmat);
  69145. }
  69146. else {
  69147. tmat = this.getAbsoluteTransform();
  69148. }
  69149. result.x = tmat.m[12];
  69150. result.y = tmat.m[13];
  69151. result.z = tmat.m[14];
  69152. }
  69153. };
  69154. /**
  69155. * Get the absolute position of the bone (world space).
  69156. * @param mesh The mesh that this bone is attached to.
  69157. * @returns The absolute position of the bone
  69158. */
  69159. Bone.prototype.getAbsolutePosition = function (mesh) {
  69160. if (mesh === void 0) { mesh = null; }
  69161. var pos = BABYLON.Vector3.Zero();
  69162. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  69163. return pos;
  69164. };
  69165. /**
  69166. * Copy the absolute position of the bone (world space) to the result param.
  69167. * @param mesh The mesh that this bone is attached to.
  69168. * @param result The vector3 to copy the absolute position to.
  69169. */
  69170. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  69171. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  69172. };
  69173. /**
  69174. * Compute the absolute transforms of this bone and its children.
  69175. */
  69176. Bone.prototype.computeAbsoluteTransforms = function () {
  69177. if (this._parent) {
  69178. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69179. }
  69180. else {
  69181. this._absoluteTransform.copyFrom(this._localMatrix);
  69182. var poseMatrix = this._skeleton.getPoseMatrix();
  69183. if (poseMatrix) {
  69184. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  69185. }
  69186. }
  69187. var children = this.children;
  69188. var len = children.length;
  69189. for (var i = 0; i < len; i++) {
  69190. children[i].computeAbsoluteTransforms();
  69191. }
  69192. };
  69193. Bone.prototype._syncScaleVector = function () {
  69194. var lm = this.getLocalMatrix();
  69195. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  69196. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  69197. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  69198. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  69199. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  69200. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  69201. this._scaleVector.x = xs * Math.sqrt(xsq);
  69202. this._scaleVector.y = ys * Math.sqrt(ysq);
  69203. this._scaleVector.z = zs * Math.sqrt(zsq);
  69204. if (this._parent) {
  69205. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  69206. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  69207. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  69208. }
  69209. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  69210. };
  69211. /**
  69212. * Get the world direction from an axis that is in the local space of the bone.
  69213. * @param localAxis The local direction that is used to compute the world direction.
  69214. * @param mesh The mesh that this bone is attached to.
  69215. * @returns The world direction
  69216. */
  69217. Bone.prototype.getDirection = function (localAxis, mesh) {
  69218. if (mesh === void 0) { mesh = null; }
  69219. var result = BABYLON.Vector3.Zero();
  69220. this.getDirectionToRef(localAxis, mesh, result);
  69221. return result;
  69222. };
  69223. /**
  69224. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  69225. * @param localAxis The local direction that is used to compute the world direction.
  69226. * @param mesh The mesh that this bone is attached to.
  69227. * @param result The vector3 that the world direction will be copied to.
  69228. */
  69229. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  69230. if (mesh === void 0) { mesh = null; }
  69231. var wm = null;
  69232. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69233. if (mesh) {
  69234. wm = mesh.getWorldMatrix();
  69235. }
  69236. this._skeleton.computeAbsoluteTransforms();
  69237. var mat = Bone._tmpMats[0];
  69238. mat.copyFrom(this.getAbsoluteTransform());
  69239. if (mesh && wm) {
  69240. mat.multiplyToRef(wm, mat);
  69241. }
  69242. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  69243. result.normalize();
  69244. };
  69245. /**
  69246. * Get the euler rotation of the bone in local or world space.
  69247. * @param space The space that the rotation should be in.
  69248. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69249. * @returns The euler rotation
  69250. */
  69251. Bone.prototype.getRotation = function (space, mesh) {
  69252. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69253. if (mesh === void 0) { mesh = null; }
  69254. var result = BABYLON.Vector3.Zero();
  69255. this.getRotationToRef(space, mesh, result);
  69256. return result;
  69257. };
  69258. /**
  69259. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  69260. * @param space The space that the rotation should be in.
  69261. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69262. * @param result The vector3 that the rotation should be copied to.
  69263. */
  69264. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  69265. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69266. if (mesh === void 0) { mesh = null; }
  69267. var quat = Bone._tmpQuat;
  69268. this.getRotationQuaternionToRef(space, mesh, quat);
  69269. quat.toEulerAnglesToRef(result);
  69270. };
  69271. /**
  69272. * Get the quaternion rotation of the bone in either local or world space.
  69273. * @param space The space that the rotation should be in.
  69274. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69275. * @returns The quaternion rotation
  69276. */
  69277. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  69278. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69279. if (mesh === void 0) { mesh = null; }
  69280. var result = BABYLON.Quaternion.Identity();
  69281. this.getRotationQuaternionToRef(space, mesh, result);
  69282. return result;
  69283. };
  69284. /**
  69285. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  69286. * @param space The space that the rotation should be in.
  69287. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69288. * @param result The quaternion that the rotation should be copied to.
  69289. */
  69290. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  69291. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69292. if (mesh === void 0) { mesh = null; }
  69293. if (space == BABYLON.Space.LOCAL) {
  69294. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69295. }
  69296. else {
  69297. var mat = Bone._tmpMats[0];
  69298. var amat = this.getAbsoluteTransform();
  69299. if (mesh) {
  69300. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69301. }
  69302. else {
  69303. mat.copyFrom(amat);
  69304. }
  69305. mat.m[0] *= this._scalingDeterminant;
  69306. mat.m[1] *= this._scalingDeterminant;
  69307. mat.m[2] *= this._scalingDeterminant;
  69308. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69309. }
  69310. };
  69311. /**
  69312. * Get the rotation matrix of the bone in local or world space.
  69313. * @param space The space that the rotation should be in.
  69314. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69315. * @returns The rotation matrix
  69316. */
  69317. Bone.prototype.getRotationMatrix = function (space, mesh) {
  69318. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69319. var result = BABYLON.Matrix.Identity();
  69320. this.getRotationMatrixToRef(space, mesh, result);
  69321. return result;
  69322. };
  69323. /**
  69324. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  69325. * @param space The space that the rotation should be in.
  69326. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69327. * @param result The quaternion that the rotation should be copied to.
  69328. */
  69329. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  69330. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69331. if (space == BABYLON.Space.LOCAL) {
  69332. this.getLocalMatrix().getRotationMatrixToRef(result);
  69333. }
  69334. else {
  69335. var mat = Bone._tmpMats[0];
  69336. var amat = this.getAbsoluteTransform();
  69337. if (mesh) {
  69338. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69339. }
  69340. else {
  69341. mat.copyFrom(amat);
  69342. }
  69343. mat.m[0] *= this._scalingDeterminant;
  69344. mat.m[1] *= this._scalingDeterminant;
  69345. mat.m[2] *= this._scalingDeterminant;
  69346. mat.getRotationMatrixToRef(result);
  69347. }
  69348. };
  69349. /**
  69350. * Get the world position of a point that is in the local space of the bone.
  69351. * @param position The local position
  69352. * @param mesh The mesh that this bone is attached to.
  69353. * @returns The world position
  69354. */
  69355. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  69356. if (mesh === void 0) { mesh = null; }
  69357. var result = BABYLON.Vector3.Zero();
  69358. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  69359. return result;
  69360. };
  69361. /**
  69362. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  69363. * @param position The local position
  69364. * @param mesh The mesh that this bone is attached to.
  69365. * @param result The vector3 that the world position should be copied to.
  69366. */
  69367. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  69368. if (mesh === void 0) { mesh = null; }
  69369. var wm = null;
  69370. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69371. if (mesh) {
  69372. wm = mesh.getWorldMatrix();
  69373. }
  69374. this._skeleton.computeAbsoluteTransforms();
  69375. var tmat = Bone._tmpMats[0];
  69376. if (mesh && wm) {
  69377. tmat.copyFrom(this.getAbsoluteTransform());
  69378. tmat.multiplyToRef(wm, tmat);
  69379. }
  69380. else {
  69381. tmat = this.getAbsoluteTransform();
  69382. }
  69383. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69384. };
  69385. /**
  69386. * Get the local position of a point that is in world space.
  69387. * @param position The world position
  69388. * @param mesh The mesh that this bone is attached to.
  69389. * @returns The local position
  69390. */
  69391. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  69392. if (mesh === void 0) { mesh = null; }
  69393. var result = BABYLON.Vector3.Zero();
  69394. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  69395. return result;
  69396. };
  69397. /**
  69398. * Get the local position of a point that is in world space and copy it to the result param.
  69399. * @param position The world position
  69400. * @param mesh The mesh that this bone is attached to.
  69401. * @param result The vector3 that the local position should be copied to.
  69402. */
  69403. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  69404. if (mesh === void 0) { mesh = null; }
  69405. var wm = null;
  69406. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69407. if (mesh) {
  69408. wm = mesh.getWorldMatrix();
  69409. }
  69410. this._skeleton.computeAbsoluteTransforms();
  69411. var tmat = Bone._tmpMats[0];
  69412. tmat.copyFrom(this.getAbsoluteTransform());
  69413. if (mesh && wm) {
  69414. tmat.multiplyToRef(wm, tmat);
  69415. }
  69416. tmat.invert();
  69417. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69418. };
  69419. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69420. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  69421. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69422. return Bone;
  69423. }(BABYLON.Node));
  69424. BABYLON.Bone = Bone;
  69425. })(BABYLON || (BABYLON = {}));
  69426. //# sourceMappingURL=babylon.bone.js.map
  69427. var BABYLON;
  69428. (function (BABYLON) {
  69429. var BoneIKController = /** @class */ (function () {
  69430. function BoneIKController(mesh, bone, options) {
  69431. this.targetPosition = BABYLON.Vector3.Zero();
  69432. this.poleTargetPosition = BABYLON.Vector3.Zero();
  69433. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  69434. this.poleAngle = 0;
  69435. this.slerpAmount = 1;
  69436. this._bone1Quat = BABYLON.Quaternion.Identity();
  69437. this._bone1Mat = BABYLON.Matrix.Identity();
  69438. this._bone2Ang = Math.PI;
  69439. this._maxAngle = Math.PI;
  69440. this._rightHandedSystem = false;
  69441. this._bendAxis = BABYLON.Vector3.Right();
  69442. this._slerping = false;
  69443. this._adjustRoll = 0;
  69444. this._bone2 = bone;
  69445. this._bone1 = bone.getParent();
  69446. if (!this._bone1) {
  69447. return;
  69448. }
  69449. this.mesh = mesh;
  69450. var bonePos = bone.getPosition();
  69451. if (bone.getAbsoluteTransform().determinant() > 0) {
  69452. this._rightHandedSystem = true;
  69453. this._bendAxis.x = 0;
  69454. this._bendAxis.y = 0;
  69455. this._bendAxis.z = -1;
  69456. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  69457. this._adjustRoll = Math.PI * .5;
  69458. this._bendAxis.z = 1;
  69459. }
  69460. }
  69461. if (this._bone1.length) {
  69462. var boneScale1 = this._bone1.getScale();
  69463. var boneScale2 = this._bone2.getScale();
  69464. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  69465. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  69466. }
  69467. else if (this._bone1.children[0]) {
  69468. mesh.computeWorldMatrix(true);
  69469. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  69470. var pos2 = this._bone2.getAbsolutePosition(mesh);
  69471. var pos3 = this._bone1.getAbsolutePosition(mesh);
  69472. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  69473. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  69474. }
  69475. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  69476. this.maxAngle = Math.PI;
  69477. if (options) {
  69478. if (options.targetMesh) {
  69479. this.targetMesh = options.targetMesh;
  69480. this.targetMesh.computeWorldMatrix(true);
  69481. }
  69482. if (options.poleTargetMesh) {
  69483. this.poleTargetMesh = options.poleTargetMesh;
  69484. this.poleTargetMesh.computeWorldMatrix(true);
  69485. }
  69486. else if (options.poleTargetBone) {
  69487. this.poleTargetBone = options.poleTargetBone;
  69488. }
  69489. else if (this._bone1.getParent()) {
  69490. this.poleTargetBone = this._bone1.getParent();
  69491. }
  69492. if (options.poleTargetLocalOffset) {
  69493. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  69494. }
  69495. if (options.poleAngle) {
  69496. this.poleAngle = options.poleAngle;
  69497. }
  69498. if (options.bendAxis) {
  69499. this._bendAxis.copyFrom(options.bendAxis);
  69500. }
  69501. if (options.maxAngle) {
  69502. this.maxAngle = options.maxAngle;
  69503. }
  69504. if (options.slerpAmount) {
  69505. this.slerpAmount = options.slerpAmount;
  69506. }
  69507. }
  69508. }
  69509. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  69510. get: function () {
  69511. return this._maxAngle;
  69512. },
  69513. set: function (value) {
  69514. this._setMaxAngle(value);
  69515. },
  69516. enumerable: true,
  69517. configurable: true
  69518. });
  69519. BoneIKController.prototype._setMaxAngle = function (ang) {
  69520. if (ang < 0) {
  69521. ang = 0;
  69522. }
  69523. if (ang > Math.PI || ang == undefined) {
  69524. ang = Math.PI;
  69525. }
  69526. this._maxAngle = ang;
  69527. var a = this._bone1Length;
  69528. var b = this._bone2Length;
  69529. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  69530. };
  69531. BoneIKController.prototype.update = function () {
  69532. var bone1 = this._bone1;
  69533. if (!bone1) {
  69534. return;
  69535. }
  69536. var target = this.targetPosition;
  69537. var poleTarget = this.poleTargetPosition;
  69538. var mat1 = BoneIKController._tmpMats[0];
  69539. var mat2 = BoneIKController._tmpMats[1];
  69540. if (this.targetMesh) {
  69541. target.copyFrom(this.targetMesh.getAbsolutePosition());
  69542. }
  69543. if (this.poleTargetBone) {
  69544. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  69545. }
  69546. else if (this.poleTargetMesh) {
  69547. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  69548. }
  69549. var bonePos = BoneIKController._tmpVecs[0];
  69550. var zaxis = BoneIKController._tmpVecs[1];
  69551. var xaxis = BoneIKController._tmpVecs[2];
  69552. var yaxis = BoneIKController._tmpVecs[3];
  69553. var upAxis = BoneIKController._tmpVecs[4];
  69554. var _tmpQuat = BoneIKController._tmpQuat;
  69555. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  69556. poleTarget.subtractToRef(bonePos, upAxis);
  69557. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  69558. upAxis.y = 1;
  69559. }
  69560. else {
  69561. upAxis.normalize();
  69562. }
  69563. target.subtractToRef(bonePos, yaxis);
  69564. yaxis.normalize();
  69565. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  69566. zaxis.normalize();
  69567. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  69568. xaxis.normalize();
  69569. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  69570. var a = this._bone1Length;
  69571. var b = this._bone2Length;
  69572. var c = BABYLON.Vector3.Distance(bonePos, target);
  69573. if (this._maxReach > 0) {
  69574. c = Math.min(this._maxReach, c);
  69575. }
  69576. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  69577. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  69578. if (acosa > 1) {
  69579. acosa = 1;
  69580. }
  69581. if (acosb > 1) {
  69582. acosb = 1;
  69583. }
  69584. if (acosa < -1) {
  69585. acosa = -1;
  69586. }
  69587. if (acosb < -1) {
  69588. acosb = -1;
  69589. }
  69590. var angA = Math.acos(acosa);
  69591. var angB = Math.acos(acosb);
  69592. var angC = -angA - angB;
  69593. if (this._rightHandedSystem) {
  69594. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  69595. mat2.multiplyToRef(mat1, mat1);
  69596. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  69597. mat2.multiplyToRef(mat1, mat1);
  69598. }
  69599. else {
  69600. var _tmpVec = BoneIKController._tmpVecs[5];
  69601. _tmpVec.copyFrom(this._bendAxis);
  69602. _tmpVec.x *= -1;
  69603. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  69604. mat2.multiplyToRef(mat1, mat1);
  69605. }
  69606. if (this.poleAngle) {
  69607. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  69608. mat1.multiplyToRef(mat2, mat1);
  69609. }
  69610. if (this._bone1) {
  69611. if (this.slerpAmount < 1) {
  69612. if (!this._slerping) {
  69613. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  69614. }
  69615. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  69616. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  69617. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  69618. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  69619. this._slerping = true;
  69620. }
  69621. else {
  69622. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  69623. this._bone1Mat.copyFrom(mat1);
  69624. this._slerping = false;
  69625. }
  69626. }
  69627. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  69628. this._bone2Ang = angC;
  69629. };
  69630. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69631. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  69632. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69633. return BoneIKController;
  69634. }());
  69635. BABYLON.BoneIKController = BoneIKController;
  69636. })(BABYLON || (BABYLON = {}));
  69637. //# sourceMappingURL=babylon.boneIKController.js.map
  69638. var BABYLON;
  69639. (function (BABYLON) {
  69640. var BoneLookController = /** @class */ (function () {
  69641. /**
  69642. * Create a BoneLookController
  69643. * @param mesh the mesh that the bone belongs to
  69644. * @param bone the bone that will be looking to the target
  69645. * @param target the target Vector3 to look at
  69646. * @param settings optional settings:
  69647. * - maxYaw: the maximum angle the bone will yaw to
  69648. * - minYaw: the minimum angle the bone will yaw to
  69649. * - maxPitch: the maximum angle the bone will pitch to
  69650. * - minPitch: the minimum angle the bone will yaw to
  69651. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  69652. * - upAxis: the up axis of the coordinate system
  69653. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69654. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  69655. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  69656. * - adjustYaw: used to make an adjustment to the yaw of the bone
  69657. * - adjustPitch: used to make an adjustment to the pitch of the bone
  69658. * - adjustRoll: used to make an adjustment to the roll of the bone
  69659. **/
  69660. function BoneLookController(mesh, bone, target, options) {
  69661. /**
  69662. * The up axis of the coordinate system that is used when the bone is rotated.
  69663. */
  69664. this.upAxis = BABYLON.Vector3.Up();
  69665. /**
  69666. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69667. */
  69668. this.upAxisSpace = BABYLON.Space.LOCAL;
  69669. /**
  69670. * Used to make an adjustment to the yaw of the bone.
  69671. */
  69672. this.adjustYaw = 0;
  69673. /**
  69674. * Used to make an adjustment to the pitch of the bone.
  69675. */
  69676. this.adjustPitch = 0;
  69677. /**
  69678. * Used to make an adjustment to the roll of the bone.
  69679. */
  69680. this.adjustRoll = 0;
  69681. /**
  69682. * 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).
  69683. */
  69684. this.slerpAmount = 1;
  69685. this._boneQuat = BABYLON.Quaternion.Identity();
  69686. this._slerping = false;
  69687. this._firstFrameSkipped = false;
  69688. this._fowardAxis = BABYLON.Vector3.Forward();
  69689. this.mesh = mesh;
  69690. this.bone = bone;
  69691. this.target = target;
  69692. if (options) {
  69693. if (options.adjustYaw) {
  69694. this.adjustYaw = options.adjustYaw;
  69695. }
  69696. if (options.adjustPitch) {
  69697. this.adjustPitch = options.adjustPitch;
  69698. }
  69699. if (options.adjustRoll) {
  69700. this.adjustRoll = options.adjustRoll;
  69701. }
  69702. if (options.maxYaw != null) {
  69703. this.maxYaw = options.maxYaw;
  69704. }
  69705. else {
  69706. this.maxYaw = Math.PI;
  69707. }
  69708. if (options.minYaw != null) {
  69709. this.minYaw = options.minYaw;
  69710. }
  69711. else {
  69712. this.minYaw = -Math.PI;
  69713. }
  69714. if (options.maxPitch != null) {
  69715. this.maxPitch = options.maxPitch;
  69716. }
  69717. else {
  69718. this.maxPitch = Math.PI;
  69719. }
  69720. if (options.minPitch != null) {
  69721. this.minPitch = options.minPitch;
  69722. }
  69723. else {
  69724. this.minPitch = -Math.PI;
  69725. }
  69726. if (options.slerpAmount != null) {
  69727. this.slerpAmount = options.slerpAmount;
  69728. }
  69729. if (options.upAxis != null) {
  69730. this.upAxis = options.upAxis;
  69731. }
  69732. if (options.upAxisSpace != null) {
  69733. this.upAxisSpace = options.upAxisSpace;
  69734. }
  69735. if (options.yawAxis != null || options.pitchAxis != null) {
  69736. var newYawAxis = BABYLON.Axis.Y;
  69737. var newPitchAxis = BABYLON.Axis.X;
  69738. if (options.yawAxis != null) {
  69739. newYawAxis = options.yawAxis.clone();
  69740. newYawAxis.normalize();
  69741. }
  69742. if (options.pitchAxis != null) {
  69743. newPitchAxis = options.pitchAxis.clone();
  69744. newPitchAxis.normalize();
  69745. }
  69746. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  69747. this._transformYawPitch = BABYLON.Matrix.Identity();
  69748. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  69749. this._transformYawPitchInv = this._transformYawPitch.clone();
  69750. this._transformYawPitch.invert();
  69751. }
  69752. }
  69753. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  69754. this.upAxisSpace = BABYLON.Space.LOCAL;
  69755. }
  69756. }
  69757. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  69758. /**
  69759. * Get/set the minimum yaw angle that the bone can look to.
  69760. */
  69761. get: function () {
  69762. return this._minYaw;
  69763. },
  69764. set: function (value) {
  69765. this._minYaw = value;
  69766. this._minYawSin = Math.sin(value);
  69767. this._minYawCos = Math.cos(value);
  69768. if (this._maxYaw != null) {
  69769. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69770. this._yawRange = this._maxYaw - this._minYaw;
  69771. }
  69772. },
  69773. enumerable: true,
  69774. configurable: true
  69775. });
  69776. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  69777. /**
  69778. * Get/set the maximum yaw angle that the bone can look to.
  69779. */
  69780. get: function () {
  69781. return this._maxYaw;
  69782. },
  69783. set: function (value) {
  69784. this._maxYaw = value;
  69785. this._maxYawSin = Math.sin(value);
  69786. this._maxYawCos = Math.cos(value);
  69787. if (this._minYaw != null) {
  69788. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69789. this._yawRange = this._maxYaw - this._minYaw;
  69790. }
  69791. },
  69792. enumerable: true,
  69793. configurable: true
  69794. });
  69795. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  69796. /**
  69797. * Get/set the minimum pitch angle that the bone can look to.
  69798. */
  69799. get: function () {
  69800. return this._minPitch;
  69801. },
  69802. set: function (value) {
  69803. this._minPitch = value;
  69804. this._minPitchTan = Math.tan(value);
  69805. },
  69806. enumerable: true,
  69807. configurable: true
  69808. });
  69809. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  69810. /**
  69811. * Get/set the maximum pitch angle that the bone can look to.
  69812. */
  69813. get: function () {
  69814. return this._maxPitch;
  69815. },
  69816. set: function (value) {
  69817. this._maxPitch = value;
  69818. this._maxPitchTan = Math.tan(value);
  69819. },
  69820. enumerable: true,
  69821. configurable: true
  69822. });
  69823. /**
  69824. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  69825. */
  69826. BoneLookController.prototype.update = function () {
  69827. //skip the first frame when slerping so that the mesh rotation is correct
  69828. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  69829. this._firstFrameSkipped = true;
  69830. return;
  69831. }
  69832. var bone = this.bone;
  69833. var bonePos = BoneLookController._tmpVecs[0];
  69834. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  69835. var target = this.target;
  69836. var _tmpMat1 = BoneLookController._tmpMats[0];
  69837. var _tmpMat2 = BoneLookController._tmpMats[1];
  69838. var mesh = this.mesh;
  69839. var parentBone = bone.getParent();
  69840. var upAxis = BoneLookController._tmpVecs[1];
  69841. upAxis.copyFrom(this.upAxis);
  69842. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  69843. if (this._transformYawPitch) {
  69844. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  69845. }
  69846. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  69847. }
  69848. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  69849. mesh.getDirectionToRef(upAxis, upAxis);
  69850. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  69851. upAxis.normalize();
  69852. }
  69853. }
  69854. var checkYaw = false;
  69855. var checkPitch = false;
  69856. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  69857. checkYaw = true;
  69858. }
  69859. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  69860. checkPitch = true;
  69861. }
  69862. if (checkYaw || checkPitch) {
  69863. var spaceMat = BoneLookController._tmpMats[2];
  69864. var spaceMatInv = BoneLookController._tmpMats[3];
  69865. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  69866. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  69867. }
  69868. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  69869. spaceMat.copyFrom(mesh.getWorldMatrix());
  69870. }
  69871. else {
  69872. var forwardAxis = BoneLookController._tmpVecs[2];
  69873. forwardAxis.copyFrom(this._fowardAxis);
  69874. if (this._transformYawPitch) {
  69875. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  69876. }
  69877. if (parentBone) {
  69878. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  69879. }
  69880. else {
  69881. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  69882. }
  69883. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  69884. rightAxis.normalize();
  69885. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  69886. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  69887. }
  69888. spaceMat.invertToRef(spaceMatInv);
  69889. var xzlen = null;
  69890. if (checkPitch) {
  69891. var localTarget = BoneLookController._tmpVecs[3];
  69892. target.subtractToRef(bonePos, localTarget);
  69893. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69894. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69895. var pitch = Math.atan2(localTarget.y, xzlen);
  69896. var newPitch = pitch;
  69897. if (pitch > this._maxPitch) {
  69898. localTarget.y = this._maxPitchTan * xzlen;
  69899. newPitch = this._maxPitch;
  69900. }
  69901. else if (pitch < this._minPitch) {
  69902. localTarget.y = this._minPitchTan * xzlen;
  69903. newPitch = this._minPitch;
  69904. }
  69905. if (pitch != newPitch) {
  69906. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69907. localTarget.addInPlace(bonePos);
  69908. target = localTarget;
  69909. }
  69910. }
  69911. if (checkYaw) {
  69912. var localTarget = BoneLookController._tmpVecs[4];
  69913. target.subtractToRef(bonePos, localTarget);
  69914. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69915. var yaw = Math.atan2(localTarget.x, localTarget.z);
  69916. var newYaw = yaw;
  69917. if (yaw > this._maxYaw || yaw < this._minYaw) {
  69918. if (xzlen == null) {
  69919. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69920. }
  69921. if (this._yawRange > Math.PI) {
  69922. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  69923. localTarget.z = this._maxYawCos * xzlen;
  69924. localTarget.x = this._maxYawSin * xzlen;
  69925. newYaw = this._maxYaw;
  69926. }
  69927. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  69928. localTarget.z = this._minYawCos * xzlen;
  69929. localTarget.x = this._minYawSin * xzlen;
  69930. newYaw = this._minYaw;
  69931. }
  69932. }
  69933. else {
  69934. if (yaw > this._maxYaw) {
  69935. localTarget.z = this._maxYawCos * xzlen;
  69936. localTarget.x = this._maxYawSin * xzlen;
  69937. newYaw = this._maxYaw;
  69938. }
  69939. else if (yaw < this._minYaw) {
  69940. localTarget.z = this._minYawCos * xzlen;
  69941. localTarget.x = this._minYawSin * xzlen;
  69942. newYaw = this._minYaw;
  69943. }
  69944. }
  69945. }
  69946. if (this._slerping && this._yawRange > Math.PI) {
  69947. //are we going to be crossing into the min/max region?
  69948. var boneFwd = BoneLookController._tmpVecs[8];
  69949. boneFwd.copyFrom(BABYLON.Axis.Z);
  69950. if (this._transformYawPitch) {
  69951. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  69952. }
  69953. var boneRotMat = BoneLookController._tmpMats[4];
  69954. this._boneQuat.toRotationMatrix(boneRotMat);
  69955. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  69956. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  69957. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  69958. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  69959. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  69960. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  69961. if (angBtwTar > angBtwMidYaw) {
  69962. if (xzlen == null) {
  69963. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69964. }
  69965. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  69966. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  69967. if (angBtwMin < angBtwMax) {
  69968. newYaw = boneYaw + Math.PI * .75;
  69969. localTarget.z = Math.cos(newYaw) * xzlen;
  69970. localTarget.x = Math.sin(newYaw) * xzlen;
  69971. }
  69972. else {
  69973. newYaw = boneYaw - Math.PI * .75;
  69974. localTarget.z = Math.cos(newYaw) * xzlen;
  69975. localTarget.x = Math.sin(newYaw) * xzlen;
  69976. }
  69977. }
  69978. }
  69979. if (yaw != newYaw) {
  69980. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69981. localTarget.addInPlace(bonePos);
  69982. target = localTarget;
  69983. }
  69984. }
  69985. }
  69986. var zaxis = BoneLookController._tmpVecs[5];
  69987. var xaxis = BoneLookController._tmpVecs[6];
  69988. var yaxis = BoneLookController._tmpVecs[7];
  69989. var _tmpQuat = BoneLookController._tmpQuat;
  69990. target.subtractToRef(bonePos, zaxis);
  69991. zaxis.normalize();
  69992. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  69993. xaxis.normalize();
  69994. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  69995. yaxis.normalize();
  69996. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  69997. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  69998. return;
  69999. }
  70000. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  70001. return;
  70002. }
  70003. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  70004. return;
  70005. }
  70006. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  70007. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  70008. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  70009. }
  70010. if (this.slerpAmount < 1) {
  70011. if (!this._slerping) {
  70012. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  70013. }
  70014. if (this._transformYawPitch) {
  70015. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  70016. }
  70017. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  70018. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  70019. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  70020. this._slerping = true;
  70021. }
  70022. else {
  70023. if (this._transformYawPitch) {
  70024. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  70025. }
  70026. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  70027. this._slerping = false;
  70028. }
  70029. };
  70030. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  70031. var angDiff = ang2 - ang1;
  70032. angDiff %= Math.PI * 2;
  70033. if (angDiff > Math.PI) {
  70034. angDiff -= Math.PI * 2;
  70035. }
  70036. else if (angDiff < -Math.PI) {
  70037. angDiff += Math.PI * 2;
  70038. }
  70039. return angDiff;
  70040. };
  70041. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  70042. ang1 %= (2 * Math.PI);
  70043. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70044. ang2 %= (2 * Math.PI);
  70045. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70046. var ab = 0;
  70047. if (ang1 < ang2) {
  70048. ab = ang2 - ang1;
  70049. }
  70050. else {
  70051. ab = ang1 - ang2;
  70052. }
  70053. if (ab > Math.PI) {
  70054. ab = Math.PI * 2 - ab;
  70055. }
  70056. return ab;
  70057. };
  70058. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  70059. ang %= (2 * Math.PI);
  70060. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  70061. ang1 %= (2 * Math.PI);
  70062. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70063. ang2 %= (2 * Math.PI);
  70064. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70065. if (ang1 < ang2) {
  70066. if (ang > ang1 && ang < ang2) {
  70067. return true;
  70068. }
  70069. }
  70070. else {
  70071. if (ang > ang2 && ang < ang1) {
  70072. return true;
  70073. }
  70074. }
  70075. return false;
  70076. };
  70077. 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()];
  70078. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  70079. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70080. return BoneLookController;
  70081. }());
  70082. BABYLON.BoneLookController = BoneLookController;
  70083. })(BABYLON || (BABYLON = {}));
  70084. //# sourceMappingURL=babylon.boneLookController.js.map
  70085. var BABYLON;
  70086. (function (BABYLON) {
  70087. var Skeleton = /** @class */ (function () {
  70088. function Skeleton(name, id, scene) {
  70089. this.name = name;
  70090. this.id = id;
  70091. this.bones = new Array();
  70092. this.needInitialSkinMatrix = false;
  70093. this._isDirty = true;
  70094. this._meshesWithPoseMatrix = new Array();
  70095. this._identity = BABYLON.Matrix.Identity();
  70096. this._ranges = {};
  70097. this._lastAbsoluteTransformsUpdateId = -1;
  70098. // Events
  70099. /**
  70100. * An event triggered before computing the skeleton's matrices
  70101. * @type {BABYLON.Observable}
  70102. */
  70103. this.onBeforeComputeObservable = new BABYLON.Observable();
  70104. this.bones = [];
  70105. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70106. scene.skeletons.push(this);
  70107. //make sure it will recalculate the matrix next time prepare is called.
  70108. this._isDirty = true;
  70109. }
  70110. // Members
  70111. Skeleton.prototype.getTransformMatrices = function (mesh) {
  70112. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  70113. return mesh._bonesTransformMatrices;
  70114. }
  70115. if (!this._transformMatrices) {
  70116. this.prepare();
  70117. }
  70118. return this._transformMatrices;
  70119. };
  70120. Skeleton.prototype.getScene = function () {
  70121. return this._scene;
  70122. };
  70123. // Methods
  70124. /**
  70125. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  70126. */
  70127. Skeleton.prototype.toString = function (fullDetails) {
  70128. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  70129. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  70130. if (fullDetails) {
  70131. ret += ", Ranges: {";
  70132. var first = true;
  70133. for (var name_1 in this._ranges) {
  70134. if (first) {
  70135. ret += ", ";
  70136. first = false;
  70137. }
  70138. ret += name_1;
  70139. }
  70140. ret += "}";
  70141. }
  70142. return ret;
  70143. };
  70144. /**
  70145. * Get bone's index searching by name
  70146. * @param {string} name is bone's name to search for
  70147. * @return {number} Indice of the bone. Returns -1 if not found
  70148. */
  70149. Skeleton.prototype.getBoneIndexByName = function (name) {
  70150. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  70151. if (this.bones[boneIndex].name === name) {
  70152. return boneIndex;
  70153. }
  70154. }
  70155. return -1;
  70156. };
  70157. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  70158. // check name not already in use
  70159. if (!this._ranges[name]) {
  70160. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  70161. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70162. if (this.bones[i].animations[0]) {
  70163. this.bones[i].animations[0].createRange(name, from, to);
  70164. }
  70165. }
  70166. }
  70167. };
  70168. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  70169. if (deleteFrames === void 0) { deleteFrames = true; }
  70170. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70171. if (this.bones[i].animations[0]) {
  70172. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  70173. }
  70174. }
  70175. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  70176. };
  70177. Skeleton.prototype.getAnimationRange = function (name) {
  70178. return this._ranges[name];
  70179. };
  70180. /**
  70181. * Returns as an Array, all AnimationRanges defined on this skeleton
  70182. */
  70183. Skeleton.prototype.getAnimationRanges = function () {
  70184. var animationRanges = [];
  70185. var name;
  70186. var i = 0;
  70187. for (name in this._ranges) {
  70188. animationRanges[i] = this._ranges[name];
  70189. i++;
  70190. }
  70191. return animationRanges;
  70192. };
  70193. /**
  70194. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  70195. */
  70196. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  70197. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70198. if (this._ranges[name] || !source.getAnimationRange(name)) {
  70199. return false;
  70200. }
  70201. var ret = true;
  70202. var frameOffset = this._getHighestAnimationFrame() + 1;
  70203. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  70204. var boneDict = {};
  70205. var sourceBones = source.bones;
  70206. var nBones;
  70207. var i;
  70208. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  70209. boneDict[sourceBones[i].name] = sourceBones[i];
  70210. }
  70211. if (this.bones.length !== sourceBones.length) {
  70212. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  70213. ret = false;
  70214. }
  70215. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  70216. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  70217. var boneName = this.bones[i].name;
  70218. var sourceBone = boneDict[boneName];
  70219. if (sourceBone) {
  70220. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  70221. }
  70222. else {
  70223. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  70224. ret = false;
  70225. }
  70226. }
  70227. // do not call createAnimationRange(), since it also is done to bones, which was already done
  70228. var range = source.getAnimationRange(name);
  70229. if (range) {
  70230. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  70231. }
  70232. return ret;
  70233. };
  70234. Skeleton.prototype.returnToRest = function () {
  70235. for (var index = 0; index < this.bones.length; index++) {
  70236. this.bones[index].returnToRest();
  70237. }
  70238. };
  70239. Skeleton.prototype._getHighestAnimationFrame = function () {
  70240. var ret = 0;
  70241. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70242. if (this.bones[i].animations[0]) {
  70243. var highest = this.bones[i].animations[0].getHighestFrame();
  70244. if (ret < highest) {
  70245. ret = highest;
  70246. }
  70247. }
  70248. }
  70249. return ret;
  70250. };
  70251. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  70252. var range = this.getAnimationRange(name);
  70253. if (!range) {
  70254. return null;
  70255. }
  70256. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  70257. };
  70258. Skeleton.prototype._markAsDirty = function () {
  70259. this._isDirty = true;
  70260. };
  70261. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  70262. this._meshesWithPoseMatrix.push(mesh);
  70263. };
  70264. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  70265. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  70266. if (index > -1) {
  70267. this._meshesWithPoseMatrix.splice(index, 1);
  70268. }
  70269. };
  70270. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  70271. this.onBeforeComputeObservable.notifyObservers(this);
  70272. for (var index = 0; index < this.bones.length; index++) {
  70273. var bone = this.bones[index];
  70274. var parentBone = bone.getParent();
  70275. if (parentBone) {
  70276. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  70277. }
  70278. else {
  70279. if (initialSkinMatrix) {
  70280. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  70281. }
  70282. else {
  70283. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  70284. }
  70285. }
  70286. if (bone._index !== -1) {
  70287. var mappedIndex = bone._index === null ? index : bone._index;
  70288. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  70289. }
  70290. }
  70291. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  70292. };
  70293. Skeleton.prototype.prepare = function () {
  70294. if (!this._isDirty) {
  70295. return;
  70296. }
  70297. if (this.needInitialSkinMatrix) {
  70298. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  70299. var mesh = this._meshesWithPoseMatrix[index];
  70300. var poseMatrix = mesh.getPoseMatrix();
  70301. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  70302. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70303. }
  70304. if (this._synchronizedWithMesh !== mesh) {
  70305. this._synchronizedWithMesh = mesh;
  70306. // Prepare bones
  70307. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  70308. var bone = this.bones[boneIndex];
  70309. if (!bone.getParent()) {
  70310. var matrix = bone.getBaseMatrix();
  70311. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  70312. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  70313. }
  70314. }
  70315. }
  70316. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  70317. }
  70318. }
  70319. else {
  70320. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  70321. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70322. }
  70323. this._computeTransformMatrices(this._transformMatrices, null);
  70324. }
  70325. this._isDirty = false;
  70326. this._scene._activeBones.addCount(this.bones.length, false);
  70327. };
  70328. Skeleton.prototype.getAnimatables = function () {
  70329. if (!this._animatables || this._animatables.length !== this.bones.length) {
  70330. this._animatables = [];
  70331. for (var index = 0; index < this.bones.length; index++) {
  70332. this._animatables.push(this.bones[index]);
  70333. }
  70334. }
  70335. return this._animatables;
  70336. };
  70337. Skeleton.prototype.clone = function (name, id) {
  70338. var result = new Skeleton(name, id || name, this._scene);
  70339. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70340. for (var index = 0; index < this.bones.length; index++) {
  70341. var source = this.bones[index];
  70342. var parentBone = null;
  70343. var parent_1 = source.getParent();
  70344. if (parent_1) {
  70345. var parentIndex = this.bones.indexOf(parent_1);
  70346. parentBone = result.bones[parentIndex];
  70347. }
  70348. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  70349. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  70350. }
  70351. if (this._ranges) {
  70352. result._ranges = {};
  70353. for (var rangeName in this._ranges) {
  70354. var range = this._ranges[rangeName];
  70355. if (range) {
  70356. result._ranges[rangeName] = range.clone();
  70357. }
  70358. }
  70359. }
  70360. this._isDirty = true;
  70361. return result;
  70362. };
  70363. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  70364. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  70365. this.bones.forEach(function (bone) {
  70366. bone.animations.forEach(function (animation) {
  70367. animation.enableBlending = true;
  70368. animation.blendingSpeed = blendingSpeed;
  70369. });
  70370. });
  70371. };
  70372. Skeleton.prototype.dispose = function () {
  70373. this._meshesWithPoseMatrix = [];
  70374. // Animations
  70375. this.getScene().stopAnimation(this);
  70376. // Remove from scene
  70377. this.getScene().removeSkeleton(this);
  70378. };
  70379. Skeleton.prototype.serialize = function () {
  70380. var serializationObject = {};
  70381. serializationObject.name = this.name;
  70382. serializationObject.id = this.id;
  70383. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  70384. serializationObject.bones = [];
  70385. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70386. for (var index = 0; index < this.bones.length; index++) {
  70387. var bone = this.bones[index];
  70388. var parent_2 = bone.getParent();
  70389. var serializedBone = {
  70390. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  70391. name: bone.name,
  70392. matrix: bone.getBaseMatrix().toArray(),
  70393. rest: bone.getRestPose().toArray()
  70394. };
  70395. serializationObject.bones.push(serializedBone);
  70396. if (bone.length) {
  70397. serializedBone.length = bone.length;
  70398. }
  70399. if (bone.animations && bone.animations.length > 0) {
  70400. serializedBone.animation = bone.animations[0].serialize();
  70401. }
  70402. serializationObject.ranges = [];
  70403. for (var name in this._ranges) {
  70404. var source = this._ranges[name];
  70405. if (!source) {
  70406. continue;
  70407. }
  70408. var range = {};
  70409. range.name = name;
  70410. range.from = source.from;
  70411. range.to = source.to;
  70412. serializationObject.ranges.push(range);
  70413. }
  70414. }
  70415. return serializationObject;
  70416. };
  70417. Skeleton.Parse = function (parsedSkeleton, scene) {
  70418. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  70419. if (parsedSkeleton.dimensionsAtRest) {
  70420. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  70421. }
  70422. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  70423. var index;
  70424. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  70425. var parsedBone = parsedSkeleton.bones[index];
  70426. var parentBone = null;
  70427. if (parsedBone.parentBoneIndex > -1) {
  70428. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  70429. }
  70430. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  70431. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  70432. if (parsedBone.length) {
  70433. bone.length = parsedBone.length;
  70434. }
  70435. if (parsedBone.animation) {
  70436. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  70437. }
  70438. }
  70439. // placed after bones, so createAnimationRange can cascade down
  70440. if (parsedSkeleton.ranges) {
  70441. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  70442. var data = parsedSkeleton.ranges[index];
  70443. skeleton.createAnimationRange(data.name, data.from, data.to);
  70444. }
  70445. }
  70446. return skeleton;
  70447. };
  70448. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  70449. if (forceUpdate === void 0) { forceUpdate = false; }
  70450. var renderId = this._scene.getRenderId();
  70451. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  70452. this.bones[0].computeAbsoluteTransforms();
  70453. this._lastAbsoluteTransformsUpdateId = renderId;
  70454. }
  70455. };
  70456. Skeleton.prototype.getPoseMatrix = function () {
  70457. var poseMatrix = null;
  70458. if (this._meshesWithPoseMatrix.length > 0) {
  70459. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  70460. }
  70461. return poseMatrix;
  70462. };
  70463. Skeleton.prototype.sortBones = function () {
  70464. var bones = new Array();
  70465. var visited = new Array(this.bones.length);
  70466. for (var index = 0; index < this.bones.length; index++) {
  70467. this._sortBones(index, bones, visited);
  70468. }
  70469. this.bones = bones;
  70470. };
  70471. Skeleton.prototype._sortBones = function (index, bones, visited) {
  70472. if (visited[index]) {
  70473. return;
  70474. }
  70475. visited[index] = true;
  70476. var bone = this.bones[index];
  70477. if (bone._index === undefined) {
  70478. bone._index = index;
  70479. }
  70480. var parentBone = bone.getParent();
  70481. if (parentBone) {
  70482. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  70483. }
  70484. bones.push(bone);
  70485. };
  70486. return Skeleton;
  70487. }());
  70488. BABYLON.Skeleton = Skeleton;
  70489. })(BABYLON || (BABYLON = {}));
  70490. //# sourceMappingURL=babylon.skeleton.js.map
  70491. var BABYLON;
  70492. (function (BABYLON) {
  70493. var SphericalPolynomial = /** @class */ (function () {
  70494. function SphericalPolynomial() {
  70495. this.x = BABYLON.Vector3.Zero();
  70496. this.y = BABYLON.Vector3.Zero();
  70497. this.z = BABYLON.Vector3.Zero();
  70498. this.xx = BABYLON.Vector3.Zero();
  70499. this.yy = BABYLON.Vector3.Zero();
  70500. this.zz = BABYLON.Vector3.Zero();
  70501. this.xy = BABYLON.Vector3.Zero();
  70502. this.yz = BABYLON.Vector3.Zero();
  70503. this.zx = BABYLON.Vector3.Zero();
  70504. }
  70505. SphericalPolynomial.prototype.addAmbient = function (color) {
  70506. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70507. this.xx = this.xx.add(colorVector);
  70508. this.yy = this.yy.add(colorVector);
  70509. this.zz = this.zz.add(colorVector);
  70510. };
  70511. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  70512. var result = new SphericalPolynomial();
  70513. result.x = harmonics.L11.scale(1.02333);
  70514. result.y = harmonics.L1_1.scale(1.02333);
  70515. result.z = harmonics.L10.scale(1.02333);
  70516. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  70517. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  70518. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  70519. result.yz = harmonics.L2_1.scale(0.858086);
  70520. result.zx = harmonics.L21.scale(0.858086);
  70521. result.xy = harmonics.L2_2.scale(0.858086);
  70522. result.scale(1.0 / Math.PI);
  70523. return result;
  70524. };
  70525. SphericalPolynomial.prototype.scale = function (scale) {
  70526. this.x = this.x.scale(scale);
  70527. this.y = this.y.scale(scale);
  70528. this.z = this.z.scale(scale);
  70529. this.xx = this.xx.scale(scale);
  70530. this.yy = this.yy.scale(scale);
  70531. this.zz = this.zz.scale(scale);
  70532. this.yz = this.yz.scale(scale);
  70533. this.zx = this.zx.scale(scale);
  70534. this.xy = this.xy.scale(scale);
  70535. };
  70536. return SphericalPolynomial;
  70537. }());
  70538. BABYLON.SphericalPolynomial = SphericalPolynomial;
  70539. var SphericalHarmonics = /** @class */ (function () {
  70540. function SphericalHarmonics() {
  70541. this.L00 = BABYLON.Vector3.Zero();
  70542. this.L1_1 = BABYLON.Vector3.Zero();
  70543. this.L10 = BABYLON.Vector3.Zero();
  70544. this.L11 = BABYLON.Vector3.Zero();
  70545. this.L2_2 = BABYLON.Vector3.Zero();
  70546. this.L2_1 = BABYLON.Vector3.Zero();
  70547. this.L20 = BABYLON.Vector3.Zero();
  70548. this.L21 = BABYLON.Vector3.Zero();
  70549. this.L22 = BABYLON.Vector3.Zero();
  70550. }
  70551. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  70552. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70553. var c = colorVector.scale(deltaSolidAngle);
  70554. this.L00 = this.L00.add(c.scale(0.282095));
  70555. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  70556. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  70557. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  70558. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  70559. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  70560. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  70561. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  70562. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  70563. };
  70564. SphericalHarmonics.prototype.scale = function (scale) {
  70565. this.L00 = this.L00.scale(scale);
  70566. this.L1_1 = this.L1_1.scale(scale);
  70567. this.L10 = this.L10.scale(scale);
  70568. this.L11 = this.L11.scale(scale);
  70569. this.L2_2 = this.L2_2.scale(scale);
  70570. this.L2_1 = this.L2_1.scale(scale);
  70571. this.L20 = this.L20.scale(scale);
  70572. this.L21 = this.L21.scale(scale);
  70573. this.L22 = this.L22.scale(scale);
  70574. };
  70575. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  70576. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  70577. //
  70578. // E_lm = A_l * L_lm
  70579. //
  70580. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  70581. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  70582. // the scaling factors are given in equation 9.
  70583. // Constant (Band 0)
  70584. this.L00 = this.L00.scale(3.141593);
  70585. // Linear (Band 1)
  70586. this.L1_1 = this.L1_1.scale(2.094395);
  70587. this.L10 = this.L10.scale(2.094395);
  70588. this.L11 = this.L11.scale(2.094395);
  70589. // Quadratic (Band 2)
  70590. this.L2_2 = this.L2_2.scale(0.785398);
  70591. this.L2_1 = this.L2_1.scale(0.785398);
  70592. this.L20 = this.L20.scale(0.785398);
  70593. this.L21 = this.L21.scale(0.785398);
  70594. this.L22 = this.L22.scale(0.785398);
  70595. };
  70596. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  70597. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  70598. // L = (1/pi) * E * rho
  70599. //
  70600. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  70601. this.scale(1.0 / Math.PI);
  70602. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  70603. // (The pixel shader must apply albedo after texture fetches, etc).
  70604. };
  70605. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  70606. var result = new SphericalHarmonics();
  70607. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  70608. result.L1_1 = polynomial.y.scale(0.977204);
  70609. result.L10 = polynomial.z.scale(0.977204);
  70610. result.L11 = polynomial.x.scale(0.977204);
  70611. result.L2_2 = polynomial.xy.scale(1.16538);
  70612. result.L2_1 = polynomial.yz.scale(1.16538);
  70613. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  70614. result.L21 = polynomial.zx.scale(1.16538);
  70615. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  70616. result.scale(Math.PI);
  70617. return result;
  70618. };
  70619. return SphericalHarmonics;
  70620. }());
  70621. BABYLON.SphericalHarmonics = SphericalHarmonics;
  70622. })(BABYLON || (BABYLON = {}));
  70623. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  70624. var BABYLON;
  70625. (function (BABYLON) {
  70626. var FileFaceOrientation = /** @class */ (function () {
  70627. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  70628. this.name = name;
  70629. this.worldAxisForNormal = worldAxisForNormal;
  70630. this.worldAxisForFileX = worldAxisForFileX;
  70631. this.worldAxisForFileY = worldAxisForFileY;
  70632. }
  70633. return FileFaceOrientation;
  70634. }());
  70635. ;
  70636. /**
  70637. * Helper class dealing with the extraction of spherical polynomial dataArray
  70638. * from a cube map.
  70639. */
  70640. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  70641. function CubeMapToSphericalPolynomialTools() {
  70642. }
  70643. /**
  70644. * Converts a texture to the according Spherical Polynomial data.
  70645. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70646. *
  70647. * @param texture The texture to extract the information from.
  70648. * @return The Spherical Polynomial data.
  70649. */
  70650. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  70651. if (!texture.isCube) {
  70652. // Only supports cube Textures currently.
  70653. return null;
  70654. }
  70655. var size = texture.getSize().width;
  70656. var right = texture.readPixels(0);
  70657. var left = texture.readPixels(1);
  70658. var up;
  70659. var down;
  70660. if (texture.isRenderTarget) {
  70661. up = texture.readPixels(3);
  70662. down = texture.readPixels(2);
  70663. }
  70664. else {
  70665. up = texture.readPixels(2);
  70666. down = texture.readPixels(3);
  70667. }
  70668. var front = texture.readPixels(4);
  70669. var back = texture.readPixels(5);
  70670. var gammaSpace = texture.gammaSpace;
  70671. // Always read as RGBA.
  70672. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  70673. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70674. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70675. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70676. }
  70677. var cubeInfo = {
  70678. size: size,
  70679. right: right,
  70680. left: left,
  70681. up: up,
  70682. down: down,
  70683. front: front,
  70684. back: back,
  70685. format: format,
  70686. type: type,
  70687. gammaSpace: gammaSpace,
  70688. };
  70689. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  70690. };
  70691. /**
  70692. * Converts a cubemap to the according Spherical Polynomial data.
  70693. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70694. *
  70695. * @param cubeInfo The Cube map to extract the information from.
  70696. * @return The Spherical Polynomial data.
  70697. */
  70698. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  70699. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  70700. var totalSolidAngle = 0.0;
  70701. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  70702. var du = 2.0 / cubeInfo.size;
  70703. var dv = du;
  70704. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  70705. var minUV = du * 0.5 - 1.0;
  70706. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70707. var fileFace = this.FileFaces[faceIndex];
  70708. var dataArray = cubeInfo[fileFace.name];
  70709. var v = minUV;
  70710. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  70711. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  70712. // Because SP is still linear, so summation is fine in that basis.
  70713. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  70714. for (var y = 0; y < cubeInfo.size; y++) {
  70715. var u = minUV;
  70716. for (var x = 0; x < cubeInfo.size; x++) {
  70717. // World direction (not normalised)
  70718. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  70719. worldDirection.normalize();
  70720. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  70721. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  70722. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  70723. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  70724. // Handle Integer types.
  70725. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70726. r /= 255;
  70727. g /= 255;
  70728. b /= 255;
  70729. }
  70730. // Handle Gamma space textures.
  70731. if (cubeInfo.gammaSpace) {
  70732. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  70733. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  70734. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  70735. }
  70736. var color = new BABYLON.Color3(r, g, b);
  70737. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  70738. totalSolidAngle += deltaSolidAngle;
  70739. u += du;
  70740. }
  70741. v += dv;
  70742. }
  70743. }
  70744. // Solid angle for entire sphere is 4*pi
  70745. var sphereSolidAngle = 4.0 * Math.PI;
  70746. // Adjust the solid angle to allow for how many faces we processed.
  70747. var facesProcessed = 6.0;
  70748. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  70749. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  70750. // This is needed because the numerical integration over the cube uses a
  70751. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  70752. // and also to compensate for accumulative error due to float precision in the summation.
  70753. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  70754. sphericalHarmonics.scale(correctionFactor);
  70755. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  70756. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  70757. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  70758. };
  70759. CubeMapToSphericalPolynomialTools.FileFaces = [
  70760. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  70761. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  70762. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  70763. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  70764. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  70765. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  70766. ];
  70767. return CubeMapToSphericalPolynomialTools;
  70768. }());
  70769. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  70770. })(BABYLON || (BABYLON = {}));
  70771. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  70772. var BABYLON;
  70773. (function (BABYLON) {
  70774. /**
  70775. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  70776. */
  70777. var PanoramaToCubeMapTools = /** @class */ (function () {
  70778. function PanoramaToCubeMapTools() {
  70779. }
  70780. /**
  70781. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  70782. *
  70783. * @param float32Array The source data.
  70784. * @param inputWidth The width of the input panorama.
  70785. * @param inputhHeight The height of the input panorama.
  70786. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  70787. * @return The cubemap data
  70788. */
  70789. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  70790. if (!float32Array) {
  70791. throw "ConvertPanoramaToCubemap: input cannot be null";
  70792. }
  70793. if (float32Array.length != inputWidth * inputHeight * 3) {
  70794. throw "ConvertPanoramaToCubemap: input size is wrong";
  70795. }
  70796. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  70797. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  70798. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  70799. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  70800. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  70801. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  70802. return {
  70803. front: textureFront,
  70804. back: textureBack,
  70805. left: textureLeft,
  70806. right: textureRight,
  70807. up: textureUp,
  70808. down: textureDown,
  70809. size: size,
  70810. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  70811. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  70812. gammaSpace: false,
  70813. };
  70814. };
  70815. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  70816. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  70817. var textureArray = new Float32Array(buffer);
  70818. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  70819. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  70820. var dy = 1 / texSize;
  70821. var fy = 0;
  70822. for (var y = 0; y < texSize; y++) {
  70823. var xv1 = faceData[0];
  70824. var xv2 = faceData[2];
  70825. for (var x = 0; x < texSize; x++) {
  70826. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  70827. v.normalize();
  70828. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  70829. // 3 channels per pixels
  70830. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  70831. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  70832. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  70833. xv1 = xv1.add(rotDX1);
  70834. xv2 = xv2.add(rotDX2);
  70835. }
  70836. fy += dy;
  70837. }
  70838. return textureArray;
  70839. };
  70840. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  70841. var theta = Math.atan2(vDir.z, vDir.x);
  70842. var phi = Math.acos(vDir.y);
  70843. while (theta < -Math.PI)
  70844. theta += 2 * Math.PI;
  70845. while (theta > Math.PI)
  70846. theta -= 2 * Math.PI;
  70847. var dx = theta / Math.PI;
  70848. var dy = phi / Math.PI;
  70849. // recenter.
  70850. dx = dx * 0.5 + 0.5;
  70851. var px = Math.round(dx * inputWidth);
  70852. if (px < 0)
  70853. px = 0;
  70854. else if (px >= inputWidth)
  70855. px = inputWidth - 1;
  70856. var py = Math.round(dy * inputHeight);
  70857. if (py < 0)
  70858. py = 0;
  70859. else if (py >= inputHeight)
  70860. py = inputHeight - 1;
  70861. var inputY = (inputHeight - py - 1);
  70862. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  70863. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  70864. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  70865. return {
  70866. r: r,
  70867. g: g,
  70868. b: b
  70869. };
  70870. };
  70871. PanoramaToCubeMapTools.FACE_FRONT = [
  70872. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70873. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70874. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70875. new BABYLON.Vector3(1.0, 1.0, -1.0)
  70876. ];
  70877. PanoramaToCubeMapTools.FACE_BACK = [
  70878. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70879. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70880. new BABYLON.Vector3(1.0, 1.0, 1.0),
  70881. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  70882. ];
  70883. PanoramaToCubeMapTools.FACE_RIGHT = [
  70884. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70885. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70886. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70887. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70888. ];
  70889. PanoramaToCubeMapTools.FACE_LEFT = [
  70890. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70891. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70892. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70893. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  70894. ];
  70895. PanoramaToCubeMapTools.FACE_DOWN = [
  70896. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70897. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70898. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70899. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70900. ];
  70901. PanoramaToCubeMapTools.FACE_UP = [
  70902. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70903. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70904. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70905. new BABYLON.Vector3(1.0, -1.0, -1.0)
  70906. ];
  70907. return PanoramaToCubeMapTools;
  70908. }());
  70909. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  70910. })(BABYLON || (BABYLON = {}));
  70911. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  70912. var BABYLON;
  70913. (function (BABYLON) {
  70914. ;
  70915. /**
  70916. * This groups tools to convert HDR texture to native colors array.
  70917. */
  70918. var HDRTools = /** @class */ (function () {
  70919. function HDRTools() {
  70920. }
  70921. HDRTools.Ldexp = function (mantissa, exponent) {
  70922. if (exponent > 1023) {
  70923. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  70924. }
  70925. if (exponent < -1074) {
  70926. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  70927. }
  70928. return mantissa * Math.pow(2, exponent);
  70929. };
  70930. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  70931. if (exponent > 0) {
  70932. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  70933. float32array[index + 0] = red * exponent;
  70934. float32array[index + 1] = green * exponent;
  70935. float32array[index + 2] = blue * exponent;
  70936. }
  70937. else {
  70938. float32array[index + 0] = 0;
  70939. float32array[index + 1] = 0;
  70940. float32array[index + 2] = 0;
  70941. }
  70942. };
  70943. HDRTools.readStringLine = function (uint8array, startIndex) {
  70944. var line = "";
  70945. var character = "";
  70946. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  70947. character = String.fromCharCode(uint8array[i]);
  70948. if (character == "\n") {
  70949. break;
  70950. }
  70951. line += character;
  70952. }
  70953. return line;
  70954. };
  70955. /**
  70956. * Reads header information from an RGBE texture stored in a native array.
  70957. * More information on this format are available here:
  70958. * https://en.wikipedia.org/wiki/RGBE_image_format
  70959. *
  70960. * @param uint8array The binary file stored in native array.
  70961. * @return The header information.
  70962. */
  70963. HDRTools.RGBE_ReadHeader = function (uint8array) {
  70964. var height = 0;
  70965. var width = 0;
  70966. var line = this.readStringLine(uint8array, 0);
  70967. if (line[0] != '#' || line[1] != '?') {
  70968. throw "Bad HDR Format.";
  70969. }
  70970. var endOfHeader = false;
  70971. var findFormat = false;
  70972. var lineIndex = 0;
  70973. do {
  70974. lineIndex += (line.length + 1);
  70975. line = this.readStringLine(uint8array, lineIndex);
  70976. if (line == "FORMAT=32-bit_rle_rgbe") {
  70977. findFormat = true;
  70978. }
  70979. else if (line.length == 0) {
  70980. endOfHeader = true;
  70981. }
  70982. } while (!endOfHeader);
  70983. if (!findFormat) {
  70984. throw "HDR Bad header format, unsupported FORMAT";
  70985. }
  70986. lineIndex += (line.length + 1);
  70987. line = this.readStringLine(uint8array, lineIndex);
  70988. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  70989. var match = sizeRegexp.exec(line);
  70990. // TODO. Support +Y and -X if needed.
  70991. if (!match || match.length < 3) {
  70992. throw "HDR Bad header format, no size";
  70993. }
  70994. width = parseInt(match[2]);
  70995. height = parseInt(match[1]);
  70996. if (width < 8 || width > 0x7fff) {
  70997. throw "HDR Bad header format, unsupported size";
  70998. }
  70999. lineIndex += (line.length + 1);
  71000. return {
  71001. height: height,
  71002. width: width,
  71003. dataPosition: lineIndex
  71004. };
  71005. };
  71006. /**
  71007. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  71008. * This RGBE texture needs to store the information as a panorama.
  71009. *
  71010. * More information on this format are available here:
  71011. * https://en.wikipedia.org/wiki/RGBE_image_format
  71012. *
  71013. * @param buffer The binary file stored in an array buffer.
  71014. * @param size The expected size of the extracted cubemap.
  71015. * @return The Cube Map information.
  71016. */
  71017. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  71018. var uint8array = new Uint8Array(buffer);
  71019. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  71020. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  71021. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  71022. return cubeMapData;
  71023. };
  71024. /**
  71025. * Returns the pixels data extracted from an RGBE texture.
  71026. * This pixels will be stored left to right up to down in the R G B order in one array.
  71027. *
  71028. * More information on this format are available here:
  71029. * https://en.wikipedia.org/wiki/RGBE_image_format
  71030. *
  71031. * @param uint8array The binary file stored in an array buffer.
  71032. * @param hdrInfo The header information of the file.
  71033. * @return The pixels data in RGB right to left up to down order.
  71034. */
  71035. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  71036. // Keep for multi format supports.
  71037. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  71038. };
  71039. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  71040. var num_scanlines = hdrInfo.height;
  71041. var scanline_width = hdrInfo.width;
  71042. var a, b, c, d, count;
  71043. var dataIndex = hdrInfo.dataPosition;
  71044. var index = 0, endIndex = 0, i = 0;
  71045. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  71046. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  71047. // 3 channels of 4 bytes per pixel in float.
  71048. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  71049. var resultArray = new Float32Array(resultBuffer);
  71050. // read in each successive scanline
  71051. while (num_scanlines > 0) {
  71052. a = uint8array[dataIndex++];
  71053. b = uint8array[dataIndex++];
  71054. c = uint8array[dataIndex++];
  71055. d = uint8array[dataIndex++];
  71056. if (a != 2 || b != 2 || (c & 0x80)) {
  71057. // this file is not run length encoded
  71058. throw "HDR Bad header format, not RLE";
  71059. }
  71060. if (((c << 8) | d) != scanline_width) {
  71061. throw "HDR Bad header format, wrong scan line width";
  71062. }
  71063. index = 0;
  71064. // read each of the four channels for the scanline into the buffer
  71065. for (i = 0; i < 4; i++) {
  71066. endIndex = (i + 1) * scanline_width;
  71067. while (index < endIndex) {
  71068. a = uint8array[dataIndex++];
  71069. b = uint8array[dataIndex++];
  71070. if (a > 128) {
  71071. // a run of the same value
  71072. count = a - 128;
  71073. if ((count == 0) || (count > endIndex - index)) {
  71074. throw "HDR Bad Format, bad scanline data (run)";
  71075. }
  71076. while (count-- > 0) {
  71077. scanLineArray[index++] = b;
  71078. }
  71079. }
  71080. else {
  71081. // a non-run
  71082. count = a;
  71083. if ((count == 0) || (count > endIndex - index)) {
  71084. throw "HDR Bad Format, bad scanline data (non-run)";
  71085. }
  71086. scanLineArray[index++] = b;
  71087. if (--count > 0) {
  71088. for (var j = 0; j < count; j++) {
  71089. scanLineArray[index++] = uint8array[dataIndex++];
  71090. }
  71091. }
  71092. }
  71093. }
  71094. }
  71095. // now convert data from buffer into floats
  71096. for (i = 0; i < scanline_width; i++) {
  71097. a = scanLineArray[i];
  71098. b = scanLineArray[i + scanline_width];
  71099. c = scanLineArray[i + 2 * scanline_width];
  71100. d = scanLineArray[i + 3 * scanline_width];
  71101. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  71102. }
  71103. num_scanlines--;
  71104. }
  71105. return resultArray;
  71106. };
  71107. return HDRTools;
  71108. }());
  71109. BABYLON.HDRTools = HDRTools;
  71110. })(BABYLON || (BABYLON = {}));
  71111. //# sourceMappingURL=babylon.hdr.js.map
  71112. var BABYLON;
  71113. (function (BABYLON) {
  71114. /**
  71115. * This represents a texture coming from an HDR input.
  71116. *
  71117. * The only supported format is currently panorama picture stored in RGBE format.
  71118. * Example of such files can be found on HDRLib: http://hdrlib.com/
  71119. */
  71120. var HDRCubeTexture = /** @class */ (function (_super) {
  71121. __extends(HDRCubeTexture, _super);
  71122. /**
  71123. * Instantiates an HDRTexture from the following parameters.
  71124. *
  71125. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  71126. * @param scene The scene the texture will be used in
  71127. * @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.
  71128. * @param noMipmap Forces to not generate the mipmap if true
  71129. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  71130. * @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)
  71131. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  71132. */
  71133. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  71134. if (noMipmap === void 0) { noMipmap = false; }
  71135. if (generateHarmonics === void 0) { generateHarmonics = true; }
  71136. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  71137. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  71138. if (onLoad === void 0) { onLoad = null; }
  71139. if (onError === void 0) { onError = null; }
  71140. var _this = _super.call(this, scene) || this;
  71141. _this._useInGammaSpace = false;
  71142. _this._generateHarmonics = true;
  71143. _this._isBABYLONPreprocessed = false;
  71144. _this._onLoad = null;
  71145. _this._onError = null;
  71146. /**
  71147. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  71148. */
  71149. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  71150. /**
  71151. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  71152. * This is usefull at run time to apply the good shader.
  71153. */
  71154. _this.isPMREM = false;
  71155. _this._isBlocking = true;
  71156. if (!url) {
  71157. return _this;
  71158. }
  71159. _this.name = url;
  71160. _this.url = url;
  71161. _this.hasAlpha = false;
  71162. _this.isCube = true;
  71163. _this._textureMatrix = BABYLON.Matrix.Identity();
  71164. _this._onLoad = onLoad;
  71165. _this._onError = onError;
  71166. _this.gammaSpace = false;
  71167. var caps = scene.getEngine().getCaps();
  71168. if (size) {
  71169. _this._isBABYLONPreprocessed = false;
  71170. _this._noMipmap = noMipmap;
  71171. _this._size = size;
  71172. _this._useInGammaSpace = useInGammaSpace;
  71173. _this._usePMREMGenerator = usePMREMGenerator &&
  71174. caps.textureLOD &&
  71175. caps.textureFloat &&
  71176. !_this._useInGammaSpace;
  71177. }
  71178. else {
  71179. _this._isBABYLONPreprocessed = true;
  71180. _this._noMipmap = false;
  71181. _this._useInGammaSpace = false;
  71182. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  71183. !_this._useInGammaSpace;
  71184. }
  71185. _this.isPMREM = _this._usePMREMGenerator;
  71186. _this._texture = _this._getFromCache(url, _this._noMipmap);
  71187. if (!_this._texture) {
  71188. if (!scene.useDelayedTextureLoading) {
  71189. _this.loadTexture();
  71190. }
  71191. else {
  71192. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71193. }
  71194. }
  71195. return _this;
  71196. }
  71197. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  71198. /**
  71199. * Gets wether or not the texture is blocking during loading.
  71200. */
  71201. get: function () {
  71202. return this._isBlocking;
  71203. },
  71204. /**
  71205. * Sets wether or not the texture is blocking during loading.
  71206. */
  71207. set: function (value) {
  71208. this._isBlocking = value;
  71209. },
  71210. enumerable: true,
  71211. configurable: true
  71212. });
  71213. /**
  71214. * Occurs when the file is a preprocessed .babylon.hdr file.
  71215. */
  71216. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  71217. var _this = this;
  71218. var mipLevels = 0;
  71219. var floatArrayView = null;
  71220. var scene = this.getScene();
  71221. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  71222. var mips = new Array();
  71223. if (!floatArrayView) {
  71224. return mips;
  71225. }
  71226. var startIndex = 30;
  71227. for (var level = 0; level < mipLevels; level++) {
  71228. mips.push([]);
  71229. // Fill each pixel of the mip level.
  71230. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  71231. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71232. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  71233. mips[level].push(faceData);
  71234. startIndex += faceSize;
  71235. }
  71236. }
  71237. return mips;
  71238. } : null;
  71239. var callback = function (buffer) {
  71240. var scene = _this.getScene();
  71241. if (!scene) {
  71242. return null;
  71243. }
  71244. // Create Native Array Views
  71245. var intArrayView = new Int32Array(buffer);
  71246. floatArrayView = new Float32Array(buffer);
  71247. // Fill header.
  71248. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  71249. _this._size = intArrayView[1]; // CubeMap max mip face size.
  71250. // Update Texture Information.
  71251. if (!_this._texture) {
  71252. return null;
  71253. }
  71254. _this._texture.updateSize(_this._size, _this._size);
  71255. // Fill polynomial information.
  71256. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  71257. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  71258. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  71259. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  71260. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  71261. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  71262. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  71263. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  71264. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  71265. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  71266. _this.sphericalPolynomial = sphericalPolynomial;
  71267. // Fill pixel data.
  71268. mipLevels = intArrayView[29]; // Number of mip levels.
  71269. var startIndex = 30;
  71270. var data = [];
  71271. var faceSize = Math.pow(_this._size, 2) * 3;
  71272. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71273. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  71274. startIndex += faceSize;
  71275. }
  71276. var results = [];
  71277. var byteArray = null;
  71278. // Push each faces.
  71279. for (var k = 0; k < 6; k++) {
  71280. var dataFace = null;
  71281. // To be deprecated.
  71282. if (version === 1) {
  71283. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  71284. dataFace = data[j];
  71285. }
  71286. // If special cases.
  71287. if (!mipmapGenerator && dataFace) {
  71288. if (!scene.getEngine().getCaps().textureFloat) {
  71289. // 3 channels of 1 bytes per pixel in bytes.
  71290. var byteBuffer = new ArrayBuffer(faceSize);
  71291. byteArray = new Uint8Array(byteBuffer);
  71292. }
  71293. for (var i = 0; i < _this._size * _this._size; i++) {
  71294. // Put in gamma space if requested.
  71295. if (_this._useInGammaSpace) {
  71296. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71297. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71298. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71299. }
  71300. // Convert to int texture for fallback.
  71301. if (byteArray) {
  71302. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71303. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71304. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71305. // May use luminance instead if the result is not accurate.
  71306. var max = Math.max(Math.max(r, g), b);
  71307. if (max > 255) {
  71308. var scale = 255 / max;
  71309. r *= scale;
  71310. g *= scale;
  71311. b *= scale;
  71312. }
  71313. byteArray[(i * 3) + 0] = r;
  71314. byteArray[(i * 3) + 1] = g;
  71315. byteArray[(i * 3) + 2] = b;
  71316. }
  71317. }
  71318. }
  71319. // Fill the array accordingly.
  71320. if (byteArray) {
  71321. results.push(byteArray);
  71322. }
  71323. else {
  71324. results.push(dataFace);
  71325. }
  71326. }
  71327. return results;
  71328. };
  71329. if (scene) {
  71330. 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);
  71331. }
  71332. };
  71333. /**
  71334. * Occurs when the file is raw .hdr file.
  71335. */
  71336. HDRCubeTexture.prototype.loadHDRTexture = function () {
  71337. var _this = this;
  71338. var callback = function (buffer) {
  71339. var scene = _this.getScene();
  71340. if (!scene) {
  71341. return null;
  71342. }
  71343. // Extract the raw linear data.
  71344. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  71345. // Generate harmonics if needed.
  71346. if (_this._generateHarmonics) {
  71347. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  71348. _this.sphericalPolynomial = sphericalPolynomial;
  71349. }
  71350. var results = [];
  71351. var byteArray = null;
  71352. // Push each faces.
  71353. for (var j = 0; j < 6; j++) {
  71354. // Create uintarray fallback.
  71355. if (!scene.getEngine().getCaps().textureFloat) {
  71356. // 3 channels of 1 bytes per pixel in bytes.
  71357. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  71358. byteArray = new Uint8Array(byteBuffer);
  71359. }
  71360. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  71361. // If special cases.
  71362. if (_this._useInGammaSpace || byteArray) {
  71363. for (var i = 0; i < _this._size * _this._size; i++) {
  71364. // Put in gamma space if requested.
  71365. if (_this._useInGammaSpace) {
  71366. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71367. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71368. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71369. }
  71370. // Convert to int texture for fallback.
  71371. if (byteArray) {
  71372. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71373. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71374. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71375. // May use luminance instead if the result is not accurate.
  71376. var max = Math.max(Math.max(r, g), b);
  71377. if (max > 255) {
  71378. var scale = 255 / max;
  71379. r *= scale;
  71380. g *= scale;
  71381. b *= scale;
  71382. }
  71383. byteArray[(i * 3) + 0] = r;
  71384. byteArray[(i * 3) + 1] = g;
  71385. byteArray[(i * 3) + 2] = b;
  71386. }
  71387. }
  71388. }
  71389. if (byteArray) {
  71390. results.push(byteArray);
  71391. }
  71392. else {
  71393. results.push(dataFace);
  71394. }
  71395. }
  71396. return results;
  71397. };
  71398. var mipmapGenerator = null;
  71399. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  71400. // if (!this._noMipmap &&
  71401. // this._usePMREMGenerator) {
  71402. // mipmapGenerator = (data: ArrayBufferView[]) => {
  71403. // // Custom setup of the generator matching with the PBR shader values.
  71404. // var generator = new BABYLON.PMREMGenerator(data,
  71405. // this._size,
  71406. // this._size,
  71407. // 0,
  71408. // 3,
  71409. // this.getScene().getEngine().getCaps().textureFloat,
  71410. // 2048,
  71411. // 0.25,
  71412. // false,
  71413. // true);
  71414. // return generator.filterCubeMap();
  71415. // };
  71416. // }
  71417. var scene = this.getScene();
  71418. if (scene) {
  71419. 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);
  71420. }
  71421. };
  71422. /**
  71423. * Starts the loading process of the texture.
  71424. */
  71425. HDRCubeTexture.prototype.loadTexture = function () {
  71426. if (this._isBABYLONPreprocessed) {
  71427. this.loadBabylonTexture();
  71428. }
  71429. else {
  71430. this.loadHDRTexture();
  71431. }
  71432. };
  71433. HDRCubeTexture.prototype.clone = function () {
  71434. var scene = this.getScene();
  71435. if (!scene) {
  71436. return this;
  71437. }
  71438. var size = (this._isBABYLONPreprocessed ? null : this._size);
  71439. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  71440. // Base texture
  71441. newTexture.level = this.level;
  71442. newTexture.wrapU = this.wrapU;
  71443. newTexture.wrapV = this.wrapV;
  71444. newTexture.coordinatesIndex = this.coordinatesIndex;
  71445. newTexture.coordinatesMode = this.coordinatesMode;
  71446. return newTexture;
  71447. };
  71448. // Methods
  71449. HDRCubeTexture.prototype.delayLoad = function () {
  71450. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71451. return;
  71452. }
  71453. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71454. this._texture = this._getFromCache(this.url, this._noMipmap);
  71455. if (!this._texture) {
  71456. this.loadTexture();
  71457. }
  71458. };
  71459. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  71460. return this._textureMatrix;
  71461. };
  71462. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71463. this._textureMatrix = value;
  71464. };
  71465. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71466. var texture = null;
  71467. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  71468. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  71469. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  71470. texture.name = parsedTexture.name;
  71471. texture.hasAlpha = parsedTexture.hasAlpha;
  71472. texture.level = parsedTexture.level;
  71473. texture.coordinatesMode = parsedTexture.coordinatesMode;
  71474. texture.isBlocking = parsedTexture.isBlocking;
  71475. }
  71476. return texture;
  71477. };
  71478. HDRCubeTexture.prototype.serialize = function () {
  71479. if (!this.name) {
  71480. return null;
  71481. }
  71482. var serializationObject = {};
  71483. serializationObject.name = this.name;
  71484. serializationObject.hasAlpha = this.hasAlpha;
  71485. serializationObject.isCube = true;
  71486. serializationObject.level = this.level;
  71487. serializationObject.size = this._size;
  71488. serializationObject.coordinatesMode = this.coordinatesMode;
  71489. serializationObject.useInGammaSpace = this._useInGammaSpace;
  71490. serializationObject.generateHarmonics = this._generateHarmonics;
  71491. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  71492. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  71493. serializationObject.customType = "BABYLON.HDRCubeTexture";
  71494. serializationObject.noMipmap = this._noMipmap;
  71495. serializationObject.isBlocking = this._isBlocking;
  71496. return serializationObject;
  71497. };
  71498. /**
  71499. * Saves as a file the data contained in the texture in a binary format.
  71500. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71501. * as the spherical used in the lighting.
  71502. * @param url The HDR file url.
  71503. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71504. * @param onError Method called if any error happens during download.
  71505. * @return The packed binary data.
  71506. */
  71507. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  71508. if (onError === void 0) { onError = null; }
  71509. var callback = function (buffer) {
  71510. var data = new Blob([buffer], { type: 'application/octet-stream' });
  71511. // Returns a URL you can use as a href.
  71512. var objUrl = window.URL.createObjectURL(data);
  71513. // Simulates a link to it and click to dowload.
  71514. var a = document.createElement("a");
  71515. document.body.appendChild(a);
  71516. a.style.display = "none";
  71517. a.href = objUrl;
  71518. a.download = "envmap.babylon.hdr";
  71519. a.click();
  71520. };
  71521. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  71522. };
  71523. /**
  71524. * Serializes the data contained in the texture in a binary format.
  71525. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71526. * as the spherical used in the lighting.
  71527. * @param url The HDR file url.
  71528. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71529. * @param onError Method called if any error happens during download.
  71530. * @return The packed binary data.
  71531. */
  71532. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  71533. if (onError === void 0) { onError = null; }
  71534. // Needs the url tho create the texture.
  71535. if (!url) {
  71536. return;
  71537. }
  71538. // Check Power of two size.
  71539. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  71540. return;
  71541. }
  71542. // Coming Back in 3.x.
  71543. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  71544. };
  71545. HDRCubeTexture._facesMapping = [
  71546. "right",
  71547. "left",
  71548. "up",
  71549. "down",
  71550. "front",
  71551. "back"
  71552. ];
  71553. return HDRCubeTexture;
  71554. }(BABYLON.BaseTexture));
  71555. BABYLON.HDRCubeTexture = HDRCubeTexture;
  71556. })(BABYLON || (BABYLON = {}));
  71557. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  71558. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  71559. // Huge respect for a such great lib.
  71560. // Earcut license:
  71561. // Copyright (c) 2016, Mapbox
  71562. //
  71563. // Permission to use, copy, modify, and/or distribute this software for any purpose
  71564. // with or without fee is hereby granted, provided that the above copyright notice
  71565. // and this permission notice appear in all copies.
  71566. //
  71567. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  71568. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  71569. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  71570. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  71571. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  71572. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  71573. // THIS SOFTWARE.
  71574. var Earcut;
  71575. (function (Earcut) {
  71576. /**
  71577. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  71578. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  71579. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  71580. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  71581. */
  71582. function earcut(data, holeIndices, dim) {
  71583. dim = dim || 2;
  71584. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  71585. if (!outerNode)
  71586. return triangles;
  71587. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  71588. if (hasHoles)
  71589. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  71590. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  71591. if (data.length > 80 * dim) {
  71592. minX = maxX = data[0];
  71593. minY = maxY = data[1];
  71594. for (var i = dim; i < outerLen; i += dim) {
  71595. x = data[i];
  71596. y = data[i + 1];
  71597. if (x < minX)
  71598. minX = x;
  71599. if (y < minY)
  71600. minY = y;
  71601. if (x > maxX)
  71602. maxX = x;
  71603. if (y > maxY)
  71604. maxY = y;
  71605. }
  71606. // minX, minY and size are later used to transform coords into integers for z-order calculation
  71607. size = Math.max(maxX - minX, maxY - minY);
  71608. }
  71609. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  71610. return triangles;
  71611. }
  71612. Earcut.earcut = earcut;
  71613. var Node = /** @class */ (function () {
  71614. function Node(i, x, y) {
  71615. this.i = i;
  71616. this.x = x;
  71617. this.y = y;
  71618. this.prev = null;
  71619. this.next = null;
  71620. this.z = null;
  71621. this.prevZ = null;
  71622. this.nextZ = null;
  71623. this.steiner = false;
  71624. }
  71625. return Node;
  71626. }());
  71627. // create a circular doubly linked list from polygon points in the specified winding order
  71628. function linkedList(data, start, end, dim, clockwise) {
  71629. var i, last = null;
  71630. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  71631. for (i = start; i < end; i += dim)
  71632. last = insertNode(i, data[i], data[i + 1], last);
  71633. }
  71634. else {
  71635. for (i = end - dim; i >= start; i -= dim)
  71636. last = insertNode(i, data[i], data[i + 1], last);
  71637. }
  71638. if (last && equals(last, last.next)) {
  71639. removeNode(last);
  71640. last = last.next;
  71641. }
  71642. return last;
  71643. }
  71644. // eliminate colinear or duplicate points
  71645. function filterPoints(start, end) {
  71646. if (!start)
  71647. return start;
  71648. if (!end)
  71649. end = start;
  71650. var p = start, again;
  71651. do {
  71652. again = false;
  71653. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  71654. removeNode(p);
  71655. p = end = p.prev;
  71656. if (p === p.next)
  71657. return undefined;
  71658. again = true;
  71659. }
  71660. else {
  71661. p = p.next;
  71662. }
  71663. } while (again || p !== end);
  71664. return end;
  71665. }
  71666. // main ear slicing loop which triangulates a polygon (given as a linked list)
  71667. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  71668. if (!ear)
  71669. return;
  71670. // interlink polygon nodes in z-order
  71671. if (!pass && size)
  71672. indexCurve(ear, minX, minY, size);
  71673. var stop = ear, prev, next;
  71674. // iterate through ears, slicing them one by one
  71675. while (ear.prev !== ear.next) {
  71676. prev = ear.prev;
  71677. next = ear.next;
  71678. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  71679. // cut off the triangle
  71680. triangles.push(prev.i / dim);
  71681. triangles.push(ear.i / dim);
  71682. triangles.push(next.i / dim);
  71683. removeNode(ear);
  71684. // skipping the next vertice leads to less sliver triangles
  71685. ear = next.next;
  71686. stop = next.next;
  71687. continue;
  71688. }
  71689. ear = next;
  71690. // if we looped through the whole remaining polygon and can't find any more ears
  71691. if (ear === stop) {
  71692. // try filtering points and slicing again
  71693. if (!pass) {
  71694. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  71695. // if this didn't work, try curing all small self-intersections locally
  71696. }
  71697. else if (pass === 1) {
  71698. ear = cureLocalIntersections(ear, triangles, dim);
  71699. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  71700. // as a last resort, try splitting the remaining polygon into two
  71701. }
  71702. else if (pass === 2) {
  71703. splitEarcut(ear, triangles, dim, minX, minY, size);
  71704. }
  71705. break;
  71706. }
  71707. }
  71708. }
  71709. // check whether a polygon node forms a valid ear with adjacent nodes
  71710. function isEar(ear) {
  71711. var a = ear.prev, b = ear, c = ear.next;
  71712. if (area(a, b, c) >= 0)
  71713. return false; // reflex, can't be an ear
  71714. // now make sure we don't have other points inside the potential ear
  71715. var p = ear.next.next;
  71716. while (p !== ear.prev) {
  71717. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71718. area(p.prev, p, p.next) >= 0)
  71719. return false;
  71720. p = p.next;
  71721. }
  71722. return true;
  71723. }
  71724. function isEarHashed(ear, minX, minY, size) {
  71725. var a = ear.prev, b = ear, c = ear.next;
  71726. if (area(a, b, c) >= 0)
  71727. return false; // reflex, can't be an ear
  71728. // triangle bbox; min & max are calculated like this for speed
  71729. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  71730. // z-order range for the current triangle bbox;
  71731. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  71732. // first look for points inside the triangle in increasing z-order
  71733. var p = ear.nextZ;
  71734. while (p && p.z <= maxZ) {
  71735. if (p !== ear.prev &&
  71736. p !== ear.next &&
  71737. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71738. area(p.prev, p, p.next) >= 0)
  71739. return false;
  71740. p = p.nextZ;
  71741. }
  71742. // then look for points in decreasing z-order
  71743. p = ear.prevZ;
  71744. while (p && p.z >= minZ) {
  71745. if (p !== ear.prev &&
  71746. p !== ear.next &&
  71747. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71748. area(p.prev, p, p.next) >= 0)
  71749. return false;
  71750. p = p.prevZ;
  71751. }
  71752. return true;
  71753. }
  71754. // go through all polygon nodes and cure small local self-intersections
  71755. function cureLocalIntersections(start, triangles, dim) {
  71756. var p = start;
  71757. do {
  71758. var a = p.prev, b = p.next.next;
  71759. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  71760. triangles.push(a.i / dim);
  71761. triangles.push(p.i / dim);
  71762. triangles.push(b.i / dim);
  71763. // remove two nodes involved
  71764. removeNode(p);
  71765. removeNode(p.next);
  71766. p = start = b;
  71767. }
  71768. p = p.next;
  71769. } while (p !== start);
  71770. return p;
  71771. }
  71772. // try splitting polygon into two and triangulate them independently
  71773. function splitEarcut(start, triangles, dim, minX, minY, size) {
  71774. // look for a valid diagonal that divides the polygon into two
  71775. var a = start;
  71776. do {
  71777. var b = a.next.next;
  71778. while (b !== a.prev) {
  71779. if (a.i !== b.i && isValidDiagonal(a, b)) {
  71780. // split the polygon in two by the diagonal
  71781. var c = splitPolygon(a, b);
  71782. // filter colinear points around the cuts
  71783. a = filterPoints(a, a.next);
  71784. c = filterPoints(c, c.next);
  71785. // run earcut on each half
  71786. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  71787. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  71788. return;
  71789. }
  71790. b = b.next;
  71791. }
  71792. a = a.next;
  71793. } while (a !== start);
  71794. }
  71795. // link every hole into the outer loop, producing a single-ring polygon without holes
  71796. function eliminateHoles(data, holeIndices, outerNode, dim) {
  71797. var queue = [], i, len, start, end, list;
  71798. for (i = 0, len = holeIndices.length; i < len; i++) {
  71799. start = holeIndices[i] * dim;
  71800. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71801. list = linkedList(data, start, end, dim, false);
  71802. if (list === list.next)
  71803. list.steiner = true;
  71804. queue.push(getLeftmost(list));
  71805. }
  71806. queue.sort(compareX);
  71807. // process holes from left to right
  71808. for (i = 0; i < queue.length; i++) {
  71809. eliminateHole(queue[i], outerNode);
  71810. outerNode = filterPoints(outerNode, outerNode.next);
  71811. }
  71812. return outerNode;
  71813. }
  71814. function compareX(a, b) {
  71815. return a.x - b.x;
  71816. }
  71817. // find a bridge between vertices that connects hole with an outer ring and and link it
  71818. function eliminateHole(hole, outerNode) {
  71819. outerNode = findHoleBridge(hole, outerNode);
  71820. if (outerNode) {
  71821. var b = splitPolygon(outerNode, hole);
  71822. filterPoints(b, b.next);
  71823. }
  71824. }
  71825. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  71826. function findHoleBridge(hole, outerNode) {
  71827. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  71828. // find a segment intersected by a ray from the hole's leftmost point to the left;
  71829. // segment's endpoint with lesser x will be potential connection point
  71830. do {
  71831. if (hy <= p.y && hy >= p.next.y) {
  71832. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  71833. if (x <= hx && x > qx) {
  71834. qx = x;
  71835. if (x === hx) {
  71836. if (hy === p.y)
  71837. return p;
  71838. if (hy === p.next.y)
  71839. return p.next;
  71840. }
  71841. m = p.x < p.next.x ? p : p.next;
  71842. }
  71843. }
  71844. p = p.next;
  71845. } while (p !== outerNode);
  71846. if (!m)
  71847. return null;
  71848. if (hx === qx)
  71849. return m.prev; // hole touches outer segment; pick lower endpoint
  71850. // look for points inside the triangle of hole point, segment intersection and endpoint;
  71851. // if there are no points found, we have a valid connection;
  71852. // otherwise choose the point of the minimum angle with the ray as connection point
  71853. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  71854. p = m.next;
  71855. while (p !== stop) {
  71856. if (hx >= p.x &&
  71857. p.x >= mx &&
  71858. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  71859. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  71860. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  71861. m = p;
  71862. tanMin = tan;
  71863. }
  71864. }
  71865. p = p.next;
  71866. }
  71867. return m;
  71868. }
  71869. // interlink polygon nodes in z-order
  71870. function indexCurve(start, minX, minY, size) {
  71871. var p = start;
  71872. do {
  71873. if (p.z === null)
  71874. p.z = zOrder(p.x, p.y, minX, minY, size);
  71875. p.prevZ = p.prev;
  71876. p.nextZ = p.next;
  71877. p = p.next;
  71878. } while (p !== start);
  71879. p.prevZ.nextZ = null;
  71880. p.prevZ = null;
  71881. sortLinked(p);
  71882. }
  71883. // Simon Tatham's linked list merge sort algorithm
  71884. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  71885. function sortLinked(list) {
  71886. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  71887. do {
  71888. p = list;
  71889. list = null;
  71890. tail = null;
  71891. numMerges = 0;
  71892. while (p) {
  71893. numMerges++;
  71894. q = p;
  71895. pSize = 0;
  71896. for (i = 0; i < inSize; i++) {
  71897. pSize++;
  71898. q = q.nextZ;
  71899. if (!q)
  71900. break;
  71901. }
  71902. qSize = inSize;
  71903. while (pSize > 0 || (qSize > 0 && q)) {
  71904. if (pSize === 0) {
  71905. e = q;
  71906. q = q.nextZ;
  71907. qSize--;
  71908. }
  71909. else if (qSize === 0 || !q) {
  71910. e = p;
  71911. p = p.nextZ;
  71912. pSize--;
  71913. }
  71914. else if (p.z <= q.z) {
  71915. e = p;
  71916. p = p.nextZ;
  71917. pSize--;
  71918. }
  71919. else {
  71920. e = q;
  71921. q = q.nextZ;
  71922. qSize--;
  71923. }
  71924. if (tail)
  71925. tail.nextZ = e;
  71926. else
  71927. list = e;
  71928. e.prevZ = tail;
  71929. tail = e;
  71930. }
  71931. p = q;
  71932. }
  71933. tail.nextZ = null;
  71934. inSize *= 2;
  71935. } while (numMerges > 1);
  71936. return list;
  71937. }
  71938. // z-order of a point given coords and size of the data bounding box
  71939. function zOrder(x, y, minX, minY, size) {
  71940. // coords are transformed into non-negative 15-bit integer range
  71941. x = 32767 * (x - minX) / size;
  71942. y = 32767 * (y - minY) / size;
  71943. x = (x | (x << 8)) & 0x00FF00FF;
  71944. x = (x | (x << 4)) & 0x0F0F0F0F;
  71945. x = (x | (x << 2)) & 0x33333333;
  71946. x = (x | (x << 1)) & 0x55555555;
  71947. y = (y | (y << 8)) & 0x00FF00FF;
  71948. y = (y | (y << 4)) & 0x0F0F0F0F;
  71949. y = (y | (y << 2)) & 0x33333333;
  71950. y = (y | (y << 1)) & 0x55555555;
  71951. return x | (y << 1);
  71952. }
  71953. // find the leftmost node of a polygon ring
  71954. function getLeftmost(start) {
  71955. var p = start, leftmost = start;
  71956. do {
  71957. if (p.x < leftmost.x)
  71958. leftmost = p;
  71959. p = p.next;
  71960. } while (p !== start);
  71961. return leftmost;
  71962. }
  71963. // check if a point lies within a convex triangle
  71964. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  71965. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  71966. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  71967. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  71968. }
  71969. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  71970. function isValidDiagonal(a, b) {
  71971. return a.next.i !== b.i &&
  71972. a.prev.i !== b.i &&
  71973. !intersectsPolygon(a, b) &&
  71974. locallyInside(a, b) &&
  71975. locallyInside(b, a) &&
  71976. middleInside(a, b);
  71977. }
  71978. // signed area of a triangle
  71979. function area(p, q, r) {
  71980. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  71981. }
  71982. // check if two points are equal
  71983. function equals(p1, p2) {
  71984. return p1.x === p2.x && p1.y === p2.y;
  71985. }
  71986. // check if two segments intersect
  71987. function intersects(p1, q1, p2, q2) {
  71988. if ((equals(p1, q1) && equals(p2, q2)) ||
  71989. (equals(p1, q2) && equals(p2, q1)))
  71990. return true;
  71991. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  71992. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  71993. }
  71994. // check if a polygon diagonal intersects any polygon segments
  71995. function intersectsPolygon(a, b) {
  71996. var p = a;
  71997. do {
  71998. if (p.i !== a.i &&
  71999. p.next.i !== a.i &&
  72000. p.i !== b.i &&
  72001. p.next.i !== b.i &&
  72002. intersects(p, p.next, a, b))
  72003. return true;
  72004. p = p.next;
  72005. } while (p !== a);
  72006. return false;
  72007. }
  72008. // check if a polygon diagonal is locally inside the polygon
  72009. function locallyInside(a, b) {
  72010. return area(a.prev, a, a.next) < 0
  72011. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  72012. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  72013. }
  72014. // check if the middle point of a polygon diagonal is inside the polygon
  72015. function middleInside(a, b) {
  72016. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  72017. do {
  72018. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  72019. inside = !inside;
  72020. p = p.next;
  72021. } while (p !== a);
  72022. return inside;
  72023. }
  72024. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  72025. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  72026. function splitPolygon(a, b) {
  72027. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  72028. a.next = b;
  72029. b.prev = a;
  72030. a2.next = an;
  72031. an.prev = a2;
  72032. b2.next = a2;
  72033. a2.prev = b2;
  72034. bp.next = b2;
  72035. b2.prev = bp;
  72036. return b2;
  72037. }
  72038. // create a node and optionally link it with previous one (in a circular doubly linked list)
  72039. function insertNode(i, x, y, last) {
  72040. var p = new Node(i, x, y);
  72041. if (!last) {
  72042. p.prev = p;
  72043. p.next = p;
  72044. }
  72045. else {
  72046. p.next = last.next;
  72047. p.prev = last;
  72048. last.next.prev = p;
  72049. last.next = p;
  72050. }
  72051. return p;
  72052. }
  72053. function removeNode(p) {
  72054. p.next.prev = p.prev;
  72055. p.prev.next = p.next;
  72056. if (p.prevZ)
  72057. p.prevZ.nextZ = p.nextZ;
  72058. if (p.nextZ)
  72059. p.nextZ.prevZ = p.prevZ;
  72060. }
  72061. /**
  72062. * return a percentage difference between the polygon area and its triangulation area;
  72063. * used to verify correctness of triangulation
  72064. */
  72065. function deviation(data, holeIndices, dim, triangles) {
  72066. var hasHoles = holeIndices && holeIndices.length;
  72067. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  72068. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  72069. if (hasHoles) {
  72070. for (var i = 0, len = holeIndices.length; i < len; i++) {
  72071. var start = holeIndices[i] * dim;
  72072. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  72073. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  72074. }
  72075. }
  72076. var trianglesArea = 0;
  72077. for (i = 0; i < triangles.length; i += 3) {
  72078. var a = triangles[i] * dim;
  72079. var b = triangles[i + 1] * dim;
  72080. var c = triangles[i + 2] * dim;
  72081. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  72082. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  72083. }
  72084. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  72085. }
  72086. Earcut.deviation = deviation;
  72087. ;
  72088. function signedArea(data, start, end, dim) {
  72089. var sum = 0;
  72090. for (var i = start, j = end - dim; i < end; i += dim) {
  72091. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  72092. j = i;
  72093. }
  72094. return sum;
  72095. }
  72096. /**
  72097. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  72098. */
  72099. function flatten(data) {
  72100. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  72101. for (var i = 0; i < data.length; i++) {
  72102. for (var j = 0; j < data[i].length; j++) {
  72103. for (var d = 0; d < dim; d++)
  72104. result.vertices.push(data[i][j][d]);
  72105. }
  72106. if (i > 0) {
  72107. holeIndex += data[i - 1].length;
  72108. result.holes.push(holeIndex);
  72109. }
  72110. }
  72111. return result;
  72112. }
  72113. Earcut.flatten = flatten;
  72114. ;
  72115. })(Earcut || (Earcut = {}));
  72116. //# sourceMappingURL=babylon.earcut.js.map
  72117. var BABYLON;
  72118. (function (BABYLON) {
  72119. var IndexedVector2 = /** @class */ (function (_super) {
  72120. __extends(IndexedVector2, _super);
  72121. function IndexedVector2(original, index) {
  72122. var _this = _super.call(this, original.x, original.y) || this;
  72123. _this.index = index;
  72124. return _this;
  72125. }
  72126. return IndexedVector2;
  72127. }(BABYLON.Vector2));
  72128. var PolygonPoints = /** @class */ (function () {
  72129. function PolygonPoints() {
  72130. this.elements = new Array();
  72131. }
  72132. PolygonPoints.prototype.add = function (originalPoints) {
  72133. var _this = this;
  72134. var result = new Array();
  72135. originalPoints.forEach(function (point) {
  72136. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  72137. var newPoint = new IndexedVector2(point, _this.elements.length);
  72138. result.push(newPoint);
  72139. _this.elements.push(newPoint);
  72140. }
  72141. });
  72142. return result;
  72143. };
  72144. PolygonPoints.prototype.computeBounds = function () {
  72145. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72146. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72147. this.elements.forEach(function (point) {
  72148. // x
  72149. if (point.x < lmin.x) {
  72150. lmin.x = point.x;
  72151. }
  72152. else if (point.x > lmax.x) {
  72153. lmax.x = point.x;
  72154. }
  72155. // y
  72156. if (point.y < lmin.y) {
  72157. lmin.y = point.y;
  72158. }
  72159. else if (point.y > lmax.y) {
  72160. lmax.y = point.y;
  72161. }
  72162. });
  72163. return {
  72164. min: lmin,
  72165. max: lmax,
  72166. width: lmax.x - lmin.x,
  72167. height: lmax.y - lmin.y
  72168. };
  72169. };
  72170. return PolygonPoints;
  72171. }());
  72172. var Polygon = /** @class */ (function () {
  72173. function Polygon() {
  72174. }
  72175. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  72176. return [
  72177. new BABYLON.Vector2(xmin, ymin),
  72178. new BABYLON.Vector2(xmax, ymin),
  72179. new BABYLON.Vector2(xmax, ymax),
  72180. new BABYLON.Vector2(xmin, ymax)
  72181. ];
  72182. };
  72183. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  72184. if (cx === void 0) { cx = 0; }
  72185. if (cy === void 0) { cy = 0; }
  72186. if (numberOfSides === void 0) { numberOfSides = 32; }
  72187. var result = new Array();
  72188. var angle = 0;
  72189. var increment = (Math.PI * 2) / numberOfSides;
  72190. for (var i = 0; i < numberOfSides; i++) {
  72191. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  72192. angle -= increment;
  72193. }
  72194. return result;
  72195. };
  72196. Polygon.Parse = function (input) {
  72197. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  72198. var i, result = [];
  72199. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  72200. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  72201. }
  72202. return result;
  72203. };
  72204. Polygon.StartingAt = function (x, y) {
  72205. return BABYLON.Path2.StartingAt(x, y);
  72206. };
  72207. return Polygon;
  72208. }());
  72209. BABYLON.Polygon = Polygon;
  72210. var PolygonMeshBuilder = /** @class */ (function () {
  72211. function PolygonMeshBuilder(name, contours, scene) {
  72212. this._points = new PolygonPoints();
  72213. this._outlinepoints = new PolygonPoints();
  72214. this._holes = new Array();
  72215. this._epoints = new Array();
  72216. this._eholes = new Array();
  72217. this._name = name;
  72218. this._scene = scene;
  72219. var points;
  72220. if (contours instanceof BABYLON.Path2) {
  72221. points = contours.getPoints();
  72222. }
  72223. else {
  72224. points = contours;
  72225. }
  72226. this._addToepoint(points);
  72227. this._points.add(points);
  72228. this._outlinepoints.add(points);
  72229. }
  72230. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  72231. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  72232. var p = points_1[_i];
  72233. this._epoints.push(p.x, p.y);
  72234. }
  72235. };
  72236. PolygonMeshBuilder.prototype.addHole = function (hole) {
  72237. this._points.add(hole);
  72238. var holepoints = new PolygonPoints();
  72239. holepoints.add(hole);
  72240. this._holes.push(holepoints);
  72241. this._eholes.push(this._epoints.length / 2);
  72242. this._addToepoint(hole);
  72243. return this;
  72244. };
  72245. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  72246. var _this = this;
  72247. if (updatable === void 0) { updatable = false; }
  72248. if (depth === void 0) { depth = 0; }
  72249. var result = new BABYLON.Mesh(this._name, this._scene);
  72250. var normals = new Array();
  72251. var positions = new Array();
  72252. var uvs = new Array();
  72253. var bounds = this._points.computeBounds();
  72254. this._points.elements.forEach(function (p) {
  72255. normals.push(0, 1.0, 0);
  72256. positions.push(p.x, 0, p.y);
  72257. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  72258. });
  72259. var indices = new Array();
  72260. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  72261. for (var i = 0; i < res.length; i++) {
  72262. indices.push(res[i]);
  72263. }
  72264. if (depth > 0) {
  72265. var positionscount = (positions.length / 3); //get the current pointcount
  72266. this._points.elements.forEach(function (p) {
  72267. normals.push(0, -1.0, 0);
  72268. positions.push(p.x, -depth, p.y);
  72269. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  72270. });
  72271. var totalCount = indices.length;
  72272. for (var i = 0; i < totalCount; i += 3) {
  72273. var i0 = indices[i + 0];
  72274. var i1 = indices[i + 1];
  72275. var i2 = indices[i + 2];
  72276. indices.push(i2 + positionscount);
  72277. indices.push(i1 + positionscount);
  72278. indices.push(i0 + positionscount);
  72279. }
  72280. //Add the sides
  72281. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  72282. this._holes.forEach(function (hole) {
  72283. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  72284. });
  72285. }
  72286. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  72287. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  72288. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  72289. result.setIndices(indices);
  72290. return result;
  72291. };
  72292. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  72293. var StartIndex = positions.length / 3;
  72294. var ulength = 0;
  72295. for (var i = 0; i < points.elements.length; i++) {
  72296. var p = points.elements[i];
  72297. var p1;
  72298. if ((i + 1) > points.elements.length - 1) {
  72299. p1 = points.elements[0];
  72300. }
  72301. else {
  72302. p1 = points.elements[i + 1];
  72303. }
  72304. positions.push(p.x, 0, p.y);
  72305. positions.push(p.x, -depth, p.y);
  72306. positions.push(p1.x, 0, p1.y);
  72307. positions.push(p1.x, -depth, p1.y);
  72308. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  72309. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  72310. var v3 = v2.subtract(v1);
  72311. var v4 = new BABYLON.Vector3(0, 1, 0);
  72312. var vn = BABYLON.Vector3.Cross(v3, v4);
  72313. vn = vn.normalize();
  72314. uvs.push(ulength / bounds.width, 0);
  72315. uvs.push(ulength / bounds.width, 1);
  72316. ulength += v3.length();
  72317. uvs.push((ulength / bounds.width), 0);
  72318. uvs.push((ulength / bounds.width), 1);
  72319. if (!flip) {
  72320. normals.push(-vn.x, -vn.y, -vn.z);
  72321. normals.push(-vn.x, -vn.y, -vn.z);
  72322. normals.push(-vn.x, -vn.y, -vn.z);
  72323. normals.push(-vn.x, -vn.y, -vn.z);
  72324. indices.push(StartIndex);
  72325. indices.push(StartIndex + 1);
  72326. indices.push(StartIndex + 2);
  72327. indices.push(StartIndex + 1);
  72328. indices.push(StartIndex + 3);
  72329. indices.push(StartIndex + 2);
  72330. }
  72331. else {
  72332. normals.push(vn.x, vn.y, vn.z);
  72333. normals.push(vn.x, vn.y, vn.z);
  72334. normals.push(vn.x, vn.y, vn.z);
  72335. normals.push(vn.x, vn.y, vn.z);
  72336. indices.push(StartIndex);
  72337. indices.push(StartIndex + 2);
  72338. indices.push(StartIndex + 1);
  72339. indices.push(StartIndex + 1);
  72340. indices.push(StartIndex + 2);
  72341. indices.push(StartIndex + 3);
  72342. }
  72343. StartIndex += 4;
  72344. }
  72345. ;
  72346. };
  72347. return PolygonMeshBuilder;
  72348. }());
  72349. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  72350. })(BABYLON || (BABYLON = {}));
  72351. //# sourceMappingURL=babylon.polygonMesh.js.map
  72352. var BABYLON;
  72353. (function (BABYLON) {
  72354. // Unique ID when we import meshes from Babylon to CSG
  72355. var currentCSGMeshId = 0;
  72356. // # class Vertex
  72357. // Represents a vertex of a polygon. Use your own vertex class instead of this
  72358. // one to provide additional features like texture coordinates and vertex
  72359. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  72360. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  72361. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  72362. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  72363. // is not used anywhere else.
  72364. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  72365. var Vertex = /** @class */ (function () {
  72366. function Vertex(pos, normal, uv) {
  72367. this.pos = pos;
  72368. this.normal = normal;
  72369. this.uv = uv;
  72370. }
  72371. Vertex.prototype.clone = function () {
  72372. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  72373. };
  72374. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  72375. // orientation of a polygon is flipped.
  72376. Vertex.prototype.flip = function () {
  72377. this.normal = this.normal.scale(-1);
  72378. };
  72379. // Create a new vertex between this vertex and `other` by linearly
  72380. // interpolating all properties using a parameter of `t`. Subclasses should
  72381. // override this to interpolate additional properties.
  72382. Vertex.prototype.interpolate = function (other, t) {
  72383. 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));
  72384. };
  72385. return Vertex;
  72386. }());
  72387. // # class Plane
  72388. // Represents a plane in 3D space.
  72389. var Plane = /** @class */ (function () {
  72390. function Plane(normal, w) {
  72391. this.normal = normal;
  72392. this.w = w;
  72393. }
  72394. Plane.FromPoints = function (a, b, c) {
  72395. var v0 = c.subtract(a);
  72396. var v1 = b.subtract(a);
  72397. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  72398. return null;
  72399. }
  72400. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  72401. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  72402. };
  72403. Plane.prototype.clone = function () {
  72404. return new Plane(this.normal.clone(), this.w);
  72405. };
  72406. Plane.prototype.flip = function () {
  72407. this.normal.scaleInPlace(-1);
  72408. this.w = -this.w;
  72409. };
  72410. // Split `polygon` by this plane if needed, then put the polygon or polygon
  72411. // fragments in the appropriate lists. Coplanar polygons go into either
  72412. // `coplanarFront` or `coplanarBack` depending on their orientation with
  72413. // respect to this plane. Polygons in front or in back of this plane go into
  72414. // either `front` or `back`.
  72415. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  72416. var COPLANAR = 0;
  72417. var FRONT = 1;
  72418. var BACK = 2;
  72419. var SPANNING = 3;
  72420. // Classify each point as well as the entire polygon into one of the above
  72421. // four classes.
  72422. var polygonType = 0;
  72423. var types = [];
  72424. var i;
  72425. var t;
  72426. for (i = 0; i < polygon.vertices.length; i++) {
  72427. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  72428. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  72429. polygonType |= type;
  72430. types.push(type);
  72431. }
  72432. // Put the polygon in the correct list, splitting it when necessary.
  72433. switch (polygonType) {
  72434. case COPLANAR:
  72435. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  72436. break;
  72437. case FRONT:
  72438. front.push(polygon);
  72439. break;
  72440. case BACK:
  72441. back.push(polygon);
  72442. break;
  72443. case SPANNING:
  72444. var f = [], b = [];
  72445. for (i = 0; i < polygon.vertices.length; i++) {
  72446. var j = (i + 1) % polygon.vertices.length;
  72447. var ti = types[i], tj = types[j];
  72448. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  72449. if (ti !== BACK)
  72450. f.push(vi);
  72451. if (ti !== FRONT)
  72452. b.push(ti !== BACK ? vi.clone() : vi);
  72453. if ((ti | tj) === SPANNING) {
  72454. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  72455. var v = vi.interpolate(vj, t);
  72456. f.push(v);
  72457. b.push(v.clone());
  72458. }
  72459. }
  72460. var poly;
  72461. if (f.length >= 3) {
  72462. poly = new Polygon(f, polygon.shared);
  72463. if (poly.plane)
  72464. front.push(poly);
  72465. }
  72466. if (b.length >= 3) {
  72467. poly = new Polygon(b, polygon.shared);
  72468. if (poly.plane)
  72469. back.push(poly);
  72470. }
  72471. break;
  72472. }
  72473. };
  72474. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  72475. // point is on the plane.
  72476. Plane.EPSILON = 1e-5;
  72477. return Plane;
  72478. }());
  72479. // # class Polygon
  72480. // Represents a convex polygon. The vertices used to initialize a polygon must
  72481. // be coplanar and form a convex loop.
  72482. //
  72483. // Each convex polygon has a `shared` property, which is shared between all
  72484. // polygons that are clones of each other or were split from the same polygon.
  72485. // This can be used to define per-polygon properties (such as surface color).
  72486. var Polygon = /** @class */ (function () {
  72487. function Polygon(vertices, shared) {
  72488. this.vertices = vertices;
  72489. this.shared = shared;
  72490. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  72491. }
  72492. Polygon.prototype.clone = function () {
  72493. var vertices = this.vertices.map(function (v) { return v.clone(); });
  72494. return new Polygon(vertices, this.shared);
  72495. };
  72496. Polygon.prototype.flip = function () {
  72497. this.vertices.reverse().map(function (v) { v.flip(); });
  72498. this.plane.flip();
  72499. };
  72500. return Polygon;
  72501. }());
  72502. // # class Node
  72503. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  72504. // by picking a polygon to split along. That polygon (and all other coplanar
  72505. // polygons) are added directly to that node and the other polygons are added to
  72506. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  72507. // no distinction between internal and leaf nodes.
  72508. var Node = /** @class */ (function () {
  72509. function Node(polygons) {
  72510. this.plane = null;
  72511. this.front = null;
  72512. this.back = null;
  72513. this.polygons = new Array();
  72514. if (polygons) {
  72515. this.build(polygons);
  72516. }
  72517. }
  72518. Node.prototype.clone = function () {
  72519. var node = new Node();
  72520. node.plane = this.plane && this.plane.clone();
  72521. node.front = this.front && this.front.clone();
  72522. node.back = this.back && this.back.clone();
  72523. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  72524. return node;
  72525. };
  72526. // Convert solid space to empty space and empty space to solid space.
  72527. Node.prototype.invert = function () {
  72528. for (var i = 0; i < this.polygons.length; i++) {
  72529. this.polygons[i].flip();
  72530. }
  72531. if (this.plane) {
  72532. this.plane.flip();
  72533. }
  72534. if (this.front) {
  72535. this.front.invert();
  72536. }
  72537. if (this.back) {
  72538. this.back.invert();
  72539. }
  72540. var temp = this.front;
  72541. this.front = this.back;
  72542. this.back = temp;
  72543. };
  72544. // Recursively remove all polygons in `polygons` that are inside this BSP
  72545. // tree.
  72546. Node.prototype.clipPolygons = function (polygons) {
  72547. if (!this.plane)
  72548. return polygons.slice();
  72549. var front = new Array(), back = new Array();
  72550. for (var i = 0; i < polygons.length; i++) {
  72551. this.plane.splitPolygon(polygons[i], front, back, front, back);
  72552. }
  72553. if (this.front) {
  72554. front = this.front.clipPolygons(front);
  72555. }
  72556. if (this.back) {
  72557. back = this.back.clipPolygons(back);
  72558. }
  72559. else {
  72560. back = [];
  72561. }
  72562. return front.concat(back);
  72563. };
  72564. // Remove all polygons in this BSP tree that are inside the other BSP tree
  72565. // `bsp`.
  72566. Node.prototype.clipTo = function (bsp) {
  72567. this.polygons = bsp.clipPolygons(this.polygons);
  72568. if (this.front)
  72569. this.front.clipTo(bsp);
  72570. if (this.back)
  72571. this.back.clipTo(bsp);
  72572. };
  72573. // Return a list of all polygons in this BSP tree.
  72574. Node.prototype.allPolygons = function () {
  72575. var polygons = this.polygons.slice();
  72576. if (this.front)
  72577. polygons = polygons.concat(this.front.allPolygons());
  72578. if (this.back)
  72579. polygons = polygons.concat(this.back.allPolygons());
  72580. return polygons;
  72581. };
  72582. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  72583. // new polygons are filtered down to the bottom of the tree and become new
  72584. // nodes there. Each set of polygons is partitioned using the first polygon
  72585. // (no heuristic is used to pick a good split).
  72586. Node.prototype.build = function (polygons) {
  72587. if (!polygons.length)
  72588. return;
  72589. if (!this.plane)
  72590. this.plane = polygons[0].plane.clone();
  72591. var front = new Array(), back = new Array();
  72592. for (var i = 0; i < polygons.length; i++) {
  72593. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  72594. }
  72595. if (front.length) {
  72596. if (!this.front)
  72597. this.front = new Node();
  72598. this.front.build(front);
  72599. }
  72600. if (back.length) {
  72601. if (!this.back)
  72602. this.back = new Node();
  72603. this.back.build(back);
  72604. }
  72605. };
  72606. return Node;
  72607. }());
  72608. var CSG = /** @class */ (function () {
  72609. function CSG() {
  72610. this.polygons = new Array();
  72611. }
  72612. // Convert BABYLON.Mesh to BABYLON.CSG
  72613. CSG.FromMesh = function (mesh) {
  72614. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  72615. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  72616. if (mesh instanceof BABYLON.Mesh) {
  72617. mesh.computeWorldMatrix(true);
  72618. matrix = mesh.getWorldMatrix();
  72619. meshPosition = mesh.position.clone();
  72620. meshRotation = mesh.rotation.clone();
  72621. if (mesh.rotationQuaternion) {
  72622. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  72623. }
  72624. meshScaling = mesh.scaling.clone();
  72625. }
  72626. else {
  72627. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  72628. }
  72629. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  72630. var subMeshes = mesh.subMeshes;
  72631. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  72632. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  72633. vertices = [];
  72634. for (var j = 0; j < 3; j++) {
  72635. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  72636. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  72637. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  72638. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  72639. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  72640. vertex = new Vertex(position, normal, uv);
  72641. vertices.push(vertex);
  72642. }
  72643. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  72644. // To handle the case of degenerated triangle
  72645. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  72646. if (polygon.plane)
  72647. polygons.push(polygon);
  72648. }
  72649. }
  72650. var csg = CSG.FromPolygons(polygons);
  72651. csg.matrix = matrix;
  72652. csg.position = meshPosition;
  72653. csg.rotation = meshRotation;
  72654. csg.scaling = meshScaling;
  72655. csg.rotationQuaternion = meshRotationQuaternion;
  72656. currentCSGMeshId++;
  72657. return csg;
  72658. };
  72659. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  72660. CSG.FromPolygons = function (polygons) {
  72661. var csg = new CSG();
  72662. csg.polygons = polygons;
  72663. return csg;
  72664. };
  72665. CSG.prototype.clone = function () {
  72666. var csg = new CSG();
  72667. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  72668. csg.copyTransformAttributes(this);
  72669. return csg;
  72670. };
  72671. CSG.prototype.union = function (csg) {
  72672. var a = new Node(this.clone().polygons);
  72673. var b = new Node(csg.clone().polygons);
  72674. a.clipTo(b);
  72675. b.clipTo(a);
  72676. b.invert();
  72677. b.clipTo(a);
  72678. b.invert();
  72679. a.build(b.allPolygons());
  72680. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72681. };
  72682. CSG.prototype.unionInPlace = function (csg) {
  72683. var a = new Node(this.polygons);
  72684. var b = new Node(csg.polygons);
  72685. a.clipTo(b);
  72686. b.clipTo(a);
  72687. b.invert();
  72688. b.clipTo(a);
  72689. b.invert();
  72690. a.build(b.allPolygons());
  72691. this.polygons = a.allPolygons();
  72692. };
  72693. CSG.prototype.subtract = function (csg) {
  72694. var a = new Node(this.clone().polygons);
  72695. var b = new Node(csg.clone().polygons);
  72696. a.invert();
  72697. a.clipTo(b);
  72698. b.clipTo(a);
  72699. b.invert();
  72700. b.clipTo(a);
  72701. b.invert();
  72702. a.build(b.allPolygons());
  72703. a.invert();
  72704. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72705. };
  72706. CSG.prototype.subtractInPlace = function (csg) {
  72707. var a = new Node(this.polygons);
  72708. var b = new Node(csg.polygons);
  72709. a.invert();
  72710. a.clipTo(b);
  72711. b.clipTo(a);
  72712. b.invert();
  72713. b.clipTo(a);
  72714. b.invert();
  72715. a.build(b.allPolygons());
  72716. a.invert();
  72717. this.polygons = a.allPolygons();
  72718. };
  72719. CSG.prototype.intersect = function (csg) {
  72720. var a = new Node(this.clone().polygons);
  72721. var b = new Node(csg.clone().polygons);
  72722. a.invert();
  72723. b.clipTo(a);
  72724. b.invert();
  72725. a.clipTo(b);
  72726. b.clipTo(a);
  72727. a.build(b.allPolygons());
  72728. a.invert();
  72729. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72730. };
  72731. CSG.prototype.intersectInPlace = function (csg) {
  72732. var a = new Node(this.polygons);
  72733. var b = new Node(csg.polygons);
  72734. a.invert();
  72735. b.clipTo(a);
  72736. b.invert();
  72737. a.clipTo(b);
  72738. b.clipTo(a);
  72739. a.build(b.allPolygons());
  72740. a.invert();
  72741. this.polygons = a.allPolygons();
  72742. };
  72743. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  72744. // not modified.
  72745. CSG.prototype.inverse = function () {
  72746. var csg = this.clone();
  72747. csg.inverseInPlace();
  72748. return csg;
  72749. };
  72750. CSG.prototype.inverseInPlace = function () {
  72751. this.polygons.map(function (p) { p.flip(); });
  72752. };
  72753. // This is used to keep meshes transformations so they can be restored
  72754. // when we build back a Babylon Mesh
  72755. // NB : All CSG operations are performed in world coordinates
  72756. CSG.prototype.copyTransformAttributes = function (csg) {
  72757. this.matrix = csg.matrix;
  72758. this.position = csg.position;
  72759. this.rotation = csg.rotation;
  72760. this.scaling = csg.scaling;
  72761. this.rotationQuaternion = csg.rotationQuaternion;
  72762. return this;
  72763. };
  72764. // Build Raw mesh from CSG
  72765. // Coordinates here are in world space
  72766. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  72767. var matrix = this.matrix.clone();
  72768. matrix.invert();
  72769. 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;
  72770. if (keepSubMeshes) {
  72771. // Sort Polygons, since subMeshes are indices range
  72772. polygons.sort(function (a, b) {
  72773. if (a.shared.meshId === b.shared.meshId) {
  72774. return a.shared.subMeshId - b.shared.subMeshId;
  72775. }
  72776. else {
  72777. return a.shared.meshId - b.shared.meshId;
  72778. }
  72779. });
  72780. }
  72781. for (var i = 0, il = polygons.length; i < il; i++) {
  72782. polygon = polygons[i];
  72783. // Building SubMeshes
  72784. if (!subMesh_dict[polygon.shared.meshId]) {
  72785. subMesh_dict[polygon.shared.meshId] = {};
  72786. }
  72787. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  72788. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  72789. indexStart: +Infinity,
  72790. indexEnd: -Infinity,
  72791. materialIndex: polygon.shared.materialIndex
  72792. };
  72793. }
  72794. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  72795. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  72796. polygonIndices[0] = 0;
  72797. polygonIndices[1] = j - 1;
  72798. polygonIndices[2] = j;
  72799. for (var k = 0; k < 3; k++) {
  72800. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  72801. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  72802. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  72803. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  72804. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  72805. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  72806. // Check if 2 points can be merged
  72807. if (!(typeof vertex_idx !== 'undefined' &&
  72808. normals[vertex_idx * 3] === localNormal.x &&
  72809. normals[vertex_idx * 3 + 1] === localNormal.y &&
  72810. normals[vertex_idx * 3 + 2] === localNormal.z &&
  72811. uvs[vertex_idx * 2] === uv.x &&
  72812. uvs[vertex_idx * 2 + 1] === uv.y)) {
  72813. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  72814. uvs.push(uv.x, uv.y);
  72815. normals.push(normal.x, normal.y, normal.z);
  72816. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  72817. }
  72818. indices.push(vertex_idx);
  72819. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  72820. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  72821. currentIndex++;
  72822. }
  72823. }
  72824. }
  72825. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  72826. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  72827. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  72828. mesh.setIndices(indices, null);
  72829. if (keepSubMeshes) {
  72830. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  72831. var materialIndexOffset = 0, materialMaxIndex;
  72832. mesh.subMeshes = new Array();
  72833. for (var m in subMesh_dict) {
  72834. materialMaxIndex = -1;
  72835. for (var sm in subMesh_dict[m]) {
  72836. subMesh_obj = subMesh_dict[m][sm];
  72837. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  72838. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  72839. }
  72840. materialIndexOffset += ++materialMaxIndex;
  72841. }
  72842. }
  72843. return mesh;
  72844. };
  72845. // Build Mesh from CSG taking material and transforms into account
  72846. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  72847. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  72848. mesh.material = material;
  72849. mesh.position.copyFrom(this.position);
  72850. mesh.rotation.copyFrom(this.rotation);
  72851. if (this.rotationQuaternion) {
  72852. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  72853. }
  72854. mesh.scaling.copyFrom(this.scaling);
  72855. mesh.computeWorldMatrix(true);
  72856. return mesh;
  72857. };
  72858. return CSG;
  72859. }());
  72860. BABYLON.CSG = CSG;
  72861. })(BABYLON || (BABYLON = {}));
  72862. //# sourceMappingURL=babylon.csg.js.map
  72863. var BABYLON;
  72864. (function (BABYLON) {
  72865. var LensFlare = /** @class */ (function () {
  72866. function LensFlare(size, position, color, imgUrl, system) {
  72867. this.size = size;
  72868. this.position = position;
  72869. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  72870. this.color = color || new BABYLON.Color3(1, 1, 1);
  72871. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  72872. this._system = system;
  72873. system.lensFlares.push(this);
  72874. }
  72875. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  72876. return new LensFlare(size, position, color, imgUrl, system);
  72877. };
  72878. LensFlare.prototype.dispose = function () {
  72879. if (this.texture) {
  72880. this.texture.dispose();
  72881. }
  72882. // Remove from scene
  72883. var index = this._system.lensFlares.indexOf(this);
  72884. this._system.lensFlares.splice(index, 1);
  72885. };
  72886. ;
  72887. return LensFlare;
  72888. }());
  72889. BABYLON.LensFlare = LensFlare;
  72890. })(BABYLON || (BABYLON = {}));
  72891. //# sourceMappingURL=babylon.lensFlare.js.map
  72892. var BABYLON;
  72893. (function (BABYLON) {
  72894. var LensFlareSystem = /** @class */ (function () {
  72895. function LensFlareSystem(name, emitter, scene) {
  72896. this.name = name;
  72897. this.lensFlares = new Array();
  72898. this.borderLimit = 300;
  72899. this.viewportBorder = 0;
  72900. this.layerMask = 0x0FFFFFFF;
  72901. this._vertexBuffers = {};
  72902. this._isEnabled = true;
  72903. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72904. this._emitter = emitter;
  72905. this.id = name;
  72906. scene.lensFlareSystems.push(this);
  72907. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  72908. var engine = scene.getEngine();
  72909. // VBO
  72910. var vertices = [];
  72911. vertices.push(1, 1);
  72912. vertices.push(-1, 1);
  72913. vertices.push(-1, -1);
  72914. vertices.push(1, -1);
  72915. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72916. // Indices
  72917. var indices = [];
  72918. indices.push(0);
  72919. indices.push(1);
  72920. indices.push(2);
  72921. indices.push(0);
  72922. indices.push(2);
  72923. indices.push(3);
  72924. this._indexBuffer = engine.createIndexBuffer(indices);
  72925. // Effects
  72926. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  72927. }
  72928. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  72929. get: function () {
  72930. return this._isEnabled;
  72931. },
  72932. set: function (value) {
  72933. this._isEnabled = value;
  72934. },
  72935. enumerable: true,
  72936. configurable: true
  72937. });
  72938. LensFlareSystem.prototype.getScene = function () {
  72939. return this._scene;
  72940. };
  72941. LensFlareSystem.prototype.getEmitter = function () {
  72942. return this._emitter;
  72943. };
  72944. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  72945. this._emitter = newEmitter;
  72946. };
  72947. LensFlareSystem.prototype.getEmitterPosition = function () {
  72948. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  72949. };
  72950. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  72951. var position = this.getEmitterPosition();
  72952. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  72953. this._positionX = position.x;
  72954. this._positionY = position.y;
  72955. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  72956. if (this.viewportBorder > 0) {
  72957. globalViewport.x -= this.viewportBorder;
  72958. globalViewport.y -= this.viewportBorder;
  72959. globalViewport.width += this.viewportBorder * 2;
  72960. globalViewport.height += this.viewportBorder * 2;
  72961. position.x += this.viewportBorder;
  72962. position.y += this.viewportBorder;
  72963. this._positionX += this.viewportBorder;
  72964. this._positionY += this.viewportBorder;
  72965. }
  72966. if (position.z > 0) {
  72967. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  72968. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  72969. return true;
  72970. }
  72971. return true;
  72972. }
  72973. return false;
  72974. };
  72975. LensFlareSystem.prototype._isVisible = function () {
  72976. if (!this._isEnabled || !this._scene.activeCamera) {
  72977. return false;
  72978. }
  72979. var emitterPosition = this.getEmitterPosition();
  72980. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  72981. var distance = direction.length();
  72982. direction.normalize();
  72983. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  72984. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  72985. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  72986. };
  72987. LensFlareSystem.prototype.render = function () {
  72988. if (!this._effect.isReady() || !this._scene.activeCamera)
  72989. return false;
  72990. var engine = this._scene.getEngine();
  72991. var viewport = this._scene.activeCamera.viewport;
  72992. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  72993. // Position
  72994. if (!this.computeEffectivePosition(globalViewport)) {
  72995. return false;
  72996. }
  72997. // Visibility
  72998. if (!this._isVisible()) {
  72999. return false;
  73000. }
  73001. // Intensity
  73002. var awayX;
  73003. var awayY;
  73004. if (this._positionX < this.borderLimit + globalViewport.x) {
  73005. awayX = this.borderLimit + globalViewport.x - this._positionX;
  73006. }
  73007. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  73008. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  73009. }
  73010. else {
  73011. awayX = 0;
  73012. }
  73013. if (this._positionY < this.borderLimit + globalViewport.y) {
  73014. awayY = this.borderLimit + globalViewport.y - this._positionY;
  73015. }
  73016. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  73017. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  73018. }
  73019. else {
  73020. awayY = 0;
  73021. }
  73022. var away = (awayX > awayY) ? awayX : awayY;
  73023. away -= this.viewportBorder;
  73024. if (away > this.borderLimit) {
  73025. away = this.borderLimit;
  73026. }
  73027. var intensity = 1.0 - (away / this.borderLimit);
  73028. if (intensity < 0) {
  73029. return false;
  73030. }
  73031. if (intensity > 1.0) {
  73032. intensity = 1.0;
  73033. }
  73034. if (this.viewportBorder > 0) {
  73035. globalViewport.x += this.viewportBorder;
  73036. globalViewport.y += this.viewportBorder;
  73037. globalViewport.width -= this.viewportBorder * 2;
  73038. globalViewport.height -= this.viewportBorder * 2;
  73039. this._positionX -= this.viewportBorder;
  73040. this._positionY -= this.viewportBorder;
  73041. }
  73042. // Position
  73043. var centerX = globalViewport.x + globalViewport.width / 2;
  73044. var centerY = globalViewport.y + globalViewport.height / 2;
  73045. var distX = centerX - this._positionX;
  73046. var distY = centerY - this._positionY;
  73047. // Effects
  73048. engine.enableEffect(this._effect);
  73049. engine.setState(false);
  73050. engine.setDepthBuffer(false);
  73051. // VBOs
  73052. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73053. // Flares
  73054. for (var index = 0; index < this.lensFlares.length; index++) {
  73055. var flare = this.lensFlares[index];
  73056. engine.setAlphaMode(flare.alphaMode);
  73057. var x = centerX - (distX * flare.position);
  73058. var y = centerY - (distY * flare.position);
  73059. var cw = flare.size;
  73060. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  73061. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  73062. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  73063. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  73064. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  73065. // Texture
  73066. this._effect.setTexture("textureSampler", flare.texture);
  73067. // Color
  73068. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  73069. // Draw order
  73070. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73071. }
  73072. engine.setDepthBuffer(true);
  73073. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73074. return true;
  73075. };
  73076. LensFlareSystem.prototype.dispose = function () {
  73077. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73078. if (vertexBuffer) {
  73079. vertexBuffer.dispose();
  73080. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73081. }
  73082. if (this._indexBuffer) {
  73083. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73084. this._indexBuffer = null;
  73085. }
  73086. while (this.lensFlares.length) {
  73087. this.lensFlares[0].dispose();
  73088. }
  73089. // Remove from scene
  73090. var index = this._scene.lensFlareSystems.indexOf(this);
  73091. this._scene.lensFlareSystems.splice(index, 1);
  73092. };
  73093. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  73094. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  73095. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  73096. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  73097. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  73098. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  73099. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  73100. var parsedFlare = parsedLensFlareSystem.flares[index];
  73101. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  73102. }
  73103. return lensFlareSystem;
  73104. };
  73105. LensFlareSystem.prototype.serialize = function () {
  73106. var serializationObject = {};
  73107. serializationObject.id = this.id;
  73108. serializationObject.name = this.name;
  73109. serializationObject.emitterId = this.getEmitter().id;
  73110. serializationObject.borderLimit = this.borderLimit;
  73111. serializationObject.flares = [];
  73112. for (var index = 0; index < this.lensFlares.length; index++) {
  73113. var flare = this.lensFlares[index];
  73114. serializationObject.flares.push({
  73115. size: flare.size,
  73116. position: flare.position,
  73117. color: flare.color.asArray(),
  73118. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  73119. });
  73120. }
  73121. return serializationObject;
  73122. };
  73123. return LensFlareSystem;
  73124. }());
  73125. BABYLON.LensFlareSystem = LensFlareSystem;
  73126. })(BABYLON || (BABYLON = {}));
  73127. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  73128. var BABYLON;
  73129. (function (BABYLON) {
  73130. /**
  73131. * This is a holder class for the physics joint created by the physics plugin.
  73132. * It holds a set of functions to control the underlying joint.
  73133. */
  73134. var PhysicsJoint = /** @class */ (function () {
  73135. function PhysicsJoint(type, jointData) {
  73136. this.type = type;
  73137. this.jointData = jointData;
  73138. jointData.nativeParams = jointData.nativeParams || {};
  73139. }
  73140. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  73141. get: function () {
  73142. return this._physicsJoint;
  73143. },
  73144. set: function (newJoint) {
  73145. if (this._physicsJoint) {
  73146. //remove from the wolrd
  73147. }
  73148. this._physicsJoint = newJoint;
  73149. },
  73150. enumerable: true,
  73151. configurable: true
  73152. });
  73153. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  73154. set: function (physicsPlugin) {
  73155. this._physicsPlugin = physicsPlugin;
  73156. },
  73157. enumerable: true,
  73158. configurable: true
  73159. });
  73160. /**
  73161. * Execute a function that is physics-plugin specific.
  73162. * @param {Function} func the function that will be executed.
  73163. * It accepts two parameters: the physics world and the physics joint.
  73164. */
  73165. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  73166. func(this._physicsPlugin.world, this._physicsJoint);
  73167. };
  73168. //TODO check if the native joints are the same
  73169. //Joint Types
  73170. PhysicsJoint.DistanceJoint = 0;
  73171. PhysicsJoint.HingeJoint = 1;
  73172. PhysicsJoint.BallAndSocketJoint = 2;
  73173. PhysicsJoint.WheelJoint = 3;
  73174. PhysicsJoint.SliderJoint = 4;
  73175. //OIMO
  73176. PhysicsJoint.PrismaticJoint = 5;
  73177. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  73178. PhysicsJoint.UniversalJoint = 6;
  73179. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  73180. //Cannon
  73181. //Similar to a Ball-Joint. Different in params
  73182. PhysicsJoint.PointToPointJoint = 8;
  73183. //Cannon only at the moment
  73184. PhysicsJoint.SpringJoint = 9;
  73185. PhysicsJoint.LockJoint = 10;
  73186. return PhysicsJoint;
  73187. }());
  73188. BABYLON.PhysicsJoint = PhysicsJoint;
  73189. /**
  73190. * A class representing a physics distance joint.
  73191. */
  73192. var DistanceJoint = /** @class */ (function (_super) {
  73193. __extends(DistanceJoint, _super);
  73194. function DistanceJoint(jointData) {
  73195. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  73196. }
  73197. /**
  73198. * Update the predefined distance.
  73199. */
  73200. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  73201. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  73202. };
  73203. return DistanceJoint;
  73204. }(PhysicsJoint));
  73205. BABYLON.DistanceJoint = DistanceJoint;
  73206. var MotorEnabledJoint = /** @class */ (function (_super) {
  73207. __extends(MotorEnabledJoint, _super);
  73208. function MotorEnabledJoint(type, jointData) {
  73209. return _super.call(this, type, jointData) || this;
  73210. }
  73211. /**
  73212. * Set the motor values.
  73213. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73214. * @param {number} force the force to apply
  73215. * @param {number} maxForce max force for this motor.
  73216. */
  73217. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  73218. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73219. };
  73220. /**
  73221. * Set the motor's limits.
  73222. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73223. */
  73224. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73225. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73226. };
  73227. return MotorEnabledJoint;
  73228. }(PhysicsJoint));
  73229. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  73230. /**
  73231. * This class represents a single hinge physics joint
  73232. */
  73233. var HingeJoint = /** @class */ (function (_super) {
  73234. __extends(HingeJoint, _super);
  73235. function HingeJoint(jointData) {
  73236. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  73237. }
  73238. /**
  73239. * Set the motor values.
  73240. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73241. * @param {number} force the force to apply
  73242. * @param {number} maxForce max force for this motor.
  73243. */
  73244. HingeJoint.prototype.setMotor = function (force, maxForce) {
  73245. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73246. };
  73247. /**
  73248. * Set the motor's limits.
  73249. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73250. */
  73251. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73252. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73253. };
  73254. return HingeJoint;
  73255. }(MotorEnabledJoint));
  73256. BABYLON.HingeJoint = HingeJoint;
  73257. /**
  73258. * This class represents a dual hinge physics joint (same as wheel joint)
  73259. */
  73260. var Hinge2Joint = /** @class */ (function (_super) {
  73261. __extends(Hinge2Joint, _super);
  73262. function Hinge2Joint(jointData) {
  73263. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  73264. }
  73265. /**
  73266. * Set the motor values.
  73267. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73268. * @param {number} force the force to apply
  73269. * @param {number} maxForce max force for this motor.
  73270. * @param {motorIndex} the motor's index, 0 or 1.
  73271. */
  73272. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  73273. if (motorIndex === void 0) { motorIndex = 0; }
  73274. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  73275. };
  73276. /**
  73277. * Set the motor limits.
  73278. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73279. * @param {number} upperLimit the upper limit
  73280. * @param {number} lowerLimit lower limit
  73281. * @param {motorIndex} the motor's index, 0 or 1.
  73282. */
  73283. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  73284. if (motorIndex === void 0) { motorIndex = 0; }
  73285. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  73286. };
  73287. return Hinge2Joint;
  73288. }(MotorEnabledJoint));
  73289. BABYLON.Hinge2Joint = Hinge2Joint;
  73290. })(BABYLON || (BABYLON = {}));
  73291. //# sourceMappingURL=babylon.physicsJoint.js.map
  73292. var BABYLON;
  73293. (function (BABYLON) {
  73294. var PhysicsImpostor = /** @class */ (function () {
  73295. function PhysicsImpostor(object, type, _options, _scene) {
  73296. if (_options === void 0) { _options = { mass: 0 }; }
  73297. var _this = this;
  73298. this.object = object;
  73299. this.type = type;
  73300. this._options = _options;
  73301. this._scene = _scene;
  73302. this._bodyUpdateRequired = false;
  73303. this._onBeforePhysicsStepCallbacks = new Array();
  73304. this._onAfterPhysicsStepCallbacks = new Array();
  73305. this._onPhysicsCollideCallbacks = [];
  73306. this._deltaPosition = BABYLON.Vector3.Zero();
  73307. this._isDisposed = false;
  73308. //temp variables for parent rotation calculations
  73309. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  73310. this._tmpQuat = new BABYLON.Quaternion();
  73311. this._tmpQuat2 = new BABYLON.Quaternion();
  73312. /**
  73313. * this function is executed by the physics engine.
  73314. */
  73315. this.beforeStep = function () {
  73316. if (!_this._physicsEngine) {
  73317. return;
  73318. }
  73319. _this.object.translate(_this._deltaPosition, -1);
  73320. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  73321. _this.object.computeWorldMatrix(false);
  73322. if (_this.object.parent && _this.object.rotationQuaternion) {
  73323. _this.getParentsRotation();
  73324. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  73325. }
  73326. else {
  73327. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  73328. }
  73329. if (!_this._options.disableBidirectionalTransformation) {
  73330. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  73331. }
  73332. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  73333. func(_this);
  73334. });
  73335. };
  73336. /**
  73337. * this function is executed by the physics engine.
  73338. */
  73339. this.afterStep = function () {
  73340. if (!_this._physicsEngine) {
  73341. return;
  73342. }
  73343. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  73344. func(_this);
  73345. });
  73346. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  73347. // object has now its world rotation. needs to be converted to local.
  73348. if (_this.object.parent && _this.object.rotationQuaternion) {
  73349. _this.getParentsRotation();
  73350. _this._tmpQuat.conjugateInPlace();
  73351. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  73352. }
  73353. // take the position set and make it the absolute position of this object.
  73354. _this.object.setAbsolutePosition(_this.object.position);
  73355. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  73356. _this.object.translate(_this._deltaPosition, 1);
  73357. };
  73358. /**
  73359. * Legacy collision detection event support
  73360. */
  73361. this.onCollideEvent = null;
  73362. //event and body object due to cannon's event-based architecture.
  73363. this.onCollide = function (e) {
  73364. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  73365. return;
  73366. }
  73367. if (!_this._physicsEngine) {
  73368. return;
  73369. }
  73370. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  73371. if (otherImpostor) {
  73372. // Legacy collision detection event support
  73373. if (_this.onCollideEvent) {
  73374. _this.onCollideEvent(_this, otherImpostor);
  73375. }
  73376. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  73377. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  73378. }).forEach(function (obj) {
  73379. obj.callback(_this, otherImpostor);
  73380. });
  73381. }
  73382. };
  73383. //sanity check!
  73384. if (!this.object) {
  73385. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  73386. return;
  73387. }
  73388. //legacy support for old syntax.
  73389. if (!this._scene && object.getScene) {
  73390. this._scene = object.getScene();
  73391. }
  73392. if (!this._scene) {
  73393. return;
  73394. }
  73395. this._physicsEngine = this._scene.getPhysicsEngine();
  73396. if (!this._physicsEngine) {
  73397. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  73398. }
  73399. else {
  73400. //set the object's quaternion, if not set
  73401. if (!this.object.rotationQuaternion) {
  73402. if (this.object.rotation) {
  73403. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  73404. }
  73405. else {
  73406. this.object.rotationQuaternion = new BABYLON.Quaternion();
  73407. }
  73408. }
  73409. //default options params
  73410. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  73411. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  73412. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  73413. this._joints = [];
  73414. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  73415. if (!this.object.parent || this._options.ignoreParent) {
  73416. this._init();
  73417. }
  73418. else if (this.object.parent.physicsImpostor) {
  73419. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  73420. }
  73421. }
  73422. }
  73423. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  73424. get: function () {
  73425. return this._isDisposed;
  73426. },
  73427. enumerable: true,
  73428. configurable: true
  73429. });
  73430. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  73431. get: function () {
  73432. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  73433. },
  73434. set: function (value) {
  73435. this.setMass(value);
  73436. },
  73437. enumerable: true,
  73438. configurable: true
  73439. });
  73440. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  73441. get: function () {
  73442. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  73443. },
  73444. set: function (value) {
  73445. if (!this._physicsEngine) {
  73446. return;
  73447. }
  73448. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  73449. },
  73450. enumerable: true,
  73451. configurable: true
  73452. });
  73453. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  73454. get: function () {
  73455. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  73456. },
  73457. set: function (value) {
  73458. if (!this._physicsEngine) {
  73459. return;
  73460. }
  73461. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  73462. },
  73463. enumerable: true,
  73464. configurable: true
  73465. });
  73466. /**
  73467. * This function will completly initialize this impostor.
  73468. * It will create a new body - but only if this mesh has no parent.
  73469. * If it has, this impostor will not be used other than to define the impostor
  73470. * of the child mesh.
  73471. */
  73472. PhysicsImpostor.prototype._init = function () {
  73473. if (!this._physicsEngine) {
  73474. return;
  73475. }
  73476. this._physicsEngine.removeImpostor(this);
  73477. this.physicsBody = null;
  73478. this._parent = this._parent || this._getPhysicsParent();
  73479. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  73480. this._physicsEngine.addImpostor(this);
  73481. }
  73482. };
  73483. PhysicsImpostor.prototype._getPhysicsParent = function () {
  73484. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  73485. var parentMesh = this.object.parent;
  73486. return parentMesh.physicsImpostor;
  73487. }
  73488. return null;
  73489. };
  73490. /**
  73491. * Should a new body be generated.
  73492. */
  73493. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  73494. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  73495. };
  73496. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  73497. this.forceUpdate();
  73498. };
  73499. /**
  73500. * Force a regeneration of this or the parent's impostor's body.
  73501. * Use under cautious - This will remove all joints already implemented.
  73502. */
  73503. PhysicsImpostor.prototype.forceUpdate = function () {
  73504. this._init();
  73505. if (this.parent && !this._options.ignoreParent) {
  73506. this.parent.forceUpdate();
  73507. }
  73508. };
  73509. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  73510. /*public get mesh(): AbstractMesh {
  73511. return this._mesh;
  73512. }*/
  73513. /**
  73514. * Gets the body that holds this impostor. Either its own, or its parent.
  73515. */
  73516. get: function () {
  73517. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  73518. },
  73519. /**
  73520. * Set the physics body. Used mainly by the physics engine/plugin
  73521. */
  73522. set: function (physicsBody) {
  73523. if (this._physicsBody && this._physicsEngine) {
  73524. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  73525. }
  73526. this._physicsBody = physicsBody;
  73527. this.resetUpdateFlags();
  73528. },
  73529. enumerable: true,
  73530. configurable: true
  73531. });
  73532. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  73533. get: function () {
  73534. return !this._options.ignoreParent && this._parent ? this._parent : null;
  73535. },
  73536. set: function (value) {
  73537. this._parent = value;
  73538. },
  73539. enumerable: true,
  73540. configurable: true
  73541. });
  73542. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  73543. this._bodyUpdateRequired = false;
  73544. };
  73545. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  73546. if (this.object.getBoundingInfo) {
  73547. var q = this.object.rotationQuaternion;
  73548. //reset rotation
  73549. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  73550. //calculate the world matrix with no rotation
  73551. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73552. var boundingInfo = this.object.getBoundingInfo();
  73553. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  73554. //bring back the rotation
  73555. this.object.rotationQuaternion = q;
  73556. //calculate the world matrix with the new rotation
  73557. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73558. return size;
  73559. }
  73560. else {
  73561. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  73562. }
  73563. };
  73564. PhysicsImpostor.prototype.getObjectCenter = function () {
  73565. if (this.object.getBoundingInfo) {
  73566. var boundingInfo = this.object.getBoundingInfo();
  73567. return boundingInfo.boundingBox.centerWorld;
  73568. }
  73569. else {
  73570. return this.object.position;
  73571. }
  73572. };
  73573. /**
  73574. * Get a specific parametes from the options parameter.
  73575. */
  73576. PhysicsImpostor.prototype.getParam = function (paramName) {
  73577. return this._options[paramName];
  73578. };
  73579. /**
  73580. * Sets a specific parameter in the options given to the physics plugin
  73581. */
  73582. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  73583. this._options[paramName] = value;
  73584. this._bodyUpdateRequired = true;
  73585. };
  73586. /**
  73587. * Specifically change the body's mass option. Won't recreate the physics body object
  73588. */
  73589. PhysicsImpostor.prototype.setMass = function (mass) {
  73590. if (this.getParam("mass") !== mass) {
  73591. this.setParam("mass", mass);
  73592. }
  73593. if (this._physicsEngine) {
  73594. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  73595. }
  73596. };
  73597. PhysicsImpostor.prototype.getLinearVelocity = function () {
  73598. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  73599. };
  73600. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  73601. if (this._physicsEngine) {
  73602. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  73603. }
  73604. };
  73605. PhysicsImpostor.prototype.getAngularVelocity = function () {
  73606. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  73607. };
  73608. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  73609. if (this._physicsEngine) {
  73610. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  73611. }
  73612. };
  73613. /**
  73614. * Execute a function with the physics plugin native code.
  73615. * Provide a function the will have two variables - the world object and the physics body object.
  73616. */
  73617. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  73618. if (this._physicsEngine) {
  73619. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  73620. }
  73621. };
  73622. /**
  73623. * Register a function that will be executed before the physics world is stepping forward.
  73624. */
  73625. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  73626. this._onBeforePhysicsStepCallbacks.push(func);
  73627. };
  73628. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  73629. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  73630. if (index > -1) {
  73631. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  73632. }
  73633. else {
  73634. BABYLON.Tools.Warn("Function to remove was not found");
  73635. }
  73636. };
  73637. /**
  73638. * Register a function that will be executed after the physics step
  73639. */
  73640. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  73641. this._onAfterPhysicsStepCallbacks.push(func);
  73642. };
  73643. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  73644. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  73645. if (index > -1) {
  73646. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  73647. }
  73648. else {
  73649. BABYLON.Tools.Warn("Function to remove was not found");
  73650. }
  73651. };
  73652. /**
  73653. * register a function that will be executed when this impostor collides against a different body.
  73654. */
  73655. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  73656. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73657. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  73658. };
  73659. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  73660. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73661. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  73662. if (index > -1) {
  73663. this._onPhysicsCollideCallbacks.splice(index, 1);
  73664. }
  73665. else {
  73666. BABYLON.Tools.Warn("Function to remove was not found");
  73667. }
  73668. };
  73669. PhysicsImpostor.prototype.getParentsRotation = function () {
  73670. var parent = this.object.parent;
  73671. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  73672. while (parent) {
  73673. if (parent.rotationQuaternion) {
  73674. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  73675. }
  73676. else {
  73677. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  73678. }
  73679. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  73680. parent = parent.parent;
  73681. }
  73682. return this._tmpQuat;
  73683. };
  73684. /**
  73685. * Apply a force
  73686. */
  73687. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  73688. if (this._physicsEngine) {
  73689. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  73690. }
  73691. return this;
  73692. };
  73693. /**
  73694. * Apply an impulse
  73695. */
  73696. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  73697. if (this._physicsEngine) {
  73698. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  73699. }
  73700. return this;
  73701. };
  73702. /**
  73703. * A help function to create a joint.
  73704. */
  73705. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  73706. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  73707. this.addJoint(otherImpostor, joint);
  73708. return this;
  73709. };
  73710. /**
  73711. * Add a joint to this impostor with a different impostor.
  73712. */
  73713. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  73714. this._joints.push({
  73715. otherImpostor: otherImpostor,
  73716. joint: joint
  73717. });
  73718. if (this._physicsEngine) {
  73719. this._physicsEngine.addJoint(this, otherImpostor, joint);
  73720. }
  73721. return this;
  73722. };
  73723. /**
  73724. * Will keep this body still, in a sleep mode.
  73725. */
  73726. PhysicsImpostor.prototype.sleep = function () {
  73727. if (this._physicsEngine) {
  73728. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  73729. }
  73730. return this;
  73731. };
  73732. /**
  73733. * Wake the body up.
  73734. */
  73735. PhysicsImpostor.prototype.wakeUp = function () {
  73736. if (this._physicsEngine) {
  73737. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  73738. }
  73739. return this;
  73740. };
  73741. PhysicsImpostor.prototype.clone = function (newObject) {
  73742. if (!newObject)
  73743. return null;
  73744. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  73745. };
  73746. PhysicsImpostor.prototype.dispose = function () {
  73747. var _this = this;
  73748. //no dispose if no physics engine is available.
  73749. if (!this._physicsEngine) {
  73750. return;
  73751. }
  73752. this._joints.forEach(function (j) {
  73753. if (_this._physicsEngine) {
  73754. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  73755. }
  73756. });
  73757. //dispose the physics body
  73758. this._physicsEngine.removeImpostor(this);
  73759. if (this.parent) {
  73760. this.parent.forceUpdate();
  73761. }
  73762. else {
  73763. /*this._object.getChildMeshes().forEach(function(mesh) {
  73764. if (mesh.physicsImpostor) {
  73765. if (disposeChildren) {
  73766. mesh.physicsImpostor.dispose();
  73767. mesh.physicsImpostor = null;
  73768. }
  73769. }
  73770. })*/
  73771. }
  73772. this._isDisposed = true;
  73773. };
  73774. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  73775. this._deltaPosition.copyFrom(position);
  73776. };
  73777. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  73778. if (!this._deltaRotation) {
  73779. this._deltaRotation = new BABYLON.Quaternion();
  73780. }
  73781. this._deltaRotation.copyFrom(rotation);
  73782. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  73783. };
  73784. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  73785. if (this._physicsEngine) {
  73786. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  73787. }
  73788. return this;
  73789. };
  73790. PhysicsImpostor.prototype.getRadius = function () {
  73791. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  73792. };
  73793. /**
  73794. * Sync a bone with this impostor
  73795. * @param bone The bone to sync to the impostor.
  73796. * @param boneMesh The mesh that the bone is influencing.
  73797. * @param jointPivot The pivot of the joint / bone in local space.
  73798. * @param distToJoint Optional distance from the impostor to the joint.
  73799. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73800. */
  73801. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  73802. var tempVec = PhysicsImpostor._tmpVecs[0];
  73803. var mesh = this.object;
  73804. if (mesh.rotationQuaternion) {
  73805. if (adjustRotation) {
  73806. var tempQuat = PhysicsImpostor._tmpQuat;
  73807. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  73808. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  73809. }
  73810. else {
  73811. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  73812. }
  73813. }
  73814. tempVec.x = 0;
  73815. tempVec.y = 0;
  73816. tempVec.z = 0;
  73817. if (jointPivot) {
  73818. tempVec.x = jointPivot.x;
  73819. tempVec.y = jointPivot.y;
  73820. tempVec.z = jointPivot.z;
  73821. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  73822. if (distToJoint === undefined || distToJoint === null) {
  73823. distToJoint = jointPivot.length();
  73824. }
  73825. tempVec.x *= distToJoint;
  73826. tempVec.y *= distToJoint;
  73827. tempVec.z *= distToJoint;
  73828. }
  73829. if (bone.getParent()) {
  73830. tempVec.addInPlace(mesh.getAbsolutePosition());
  73831. bone.setAbsolutePosition(tempVec, boneMesh);
  73832. }
  73833. else {
  73834. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  73835. boneMesh.position.x -= tempVec.x;
  73836. boneMesh.position.y -= tempVec.y;
  73837. boneMesh.position.z -= tempVec.z;
  73838. }
  73839. };
  73840. /**
  73841. * Sync impostor to a bone
  73842. * @param bone The bone that the impostor will be synced to.
  73843. * @param boneMesh The mesh that the bone is influencing.
  73844. * @param jointPivot The pivot of the joint / bone in local space.
  73845. * @param distToJoint Optional distance from the impostor to the joint.
  73846. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73847. * @param boneAxis Optional vector3 axis the bone is aligned with
  73848. */
  73849. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  73850. var mesh = this.object;
  73851. if (mesh.rotationQuaternion) {
  73852. if (adjustRotation) {
  73853. var tempQuat = PhysicsImpostor._tmpQuat;
  73854. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  73855. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  73856. }
  73857. else {
  73858. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  73859. }
  73860. }
  73861. var pos = PhysicsImpostor._tmpVecs[0];
  73862. var boneDir = PhysicsImpostor._tmpVecs[1];
  73863. if (!boneAxis) {
  73864. boneAxis = PhysicsImpostor._tmpVecs[2];
  73865. boneAxis.x = 0;
  73866. boneAxis.y = 1;
  73867. boneAxis.z = 0;
  73868. }
  73869. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  73870. bone.getAbsolutePositionToRef(boneMesh, pos);
  73871. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  73872. distToJoint = jointPivot.length();
  73873. }
  73874. if (distToJoint !== undefined && distToJoint !== null) {
  73875. pos.x += boneDir.x * distToJoint;
  73876. pos.y += boneDir.y * distToJoint;
  73877. pos.z += boneDir.z * distToJoint;
  73878. }
  73879. mesh.setAbsolutePosition(pos);
  73880. };
  73881. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  73882. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  73883. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73884. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  73885. //Impostor types
  73886. PhysicsImpostor.NoImpostor = 0;
  73887. PhysicsImpostor.SphereImpostor = 1;
  73888. PhysicsImpostor.BoxImpostor = 2;
  73889. PhysicsImpostor.PlaneImpostor = 3;
  73890. PhysicsImpostor.MeshImpostor = 4;
  73891. PhysicsImpostor.CylinderImpostor = 7;
  73892. PhysicsImpostor.ParticleImpostor = 8;
  73893. PhysicsImpostor.HeightmapImpostor = 9;
  73894. return PhysicsImpostor;
  73895. }());
  73896. BABYLON.PhysicsImpostor = PhysicsImpostor;
  73897. })(BABYLON || (BABYLON = {}));
  73898. //# sourceMappingURL=babylon.physicsImpostor.js.map
  73899. var BABYLON;
  73900. (function (BABYLON) {
  73901. var PhysicsEngine = /** @class */ (function () {
  73902. function PhysicsEngine(gravity, _physicsPlugin) {
  73903. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  73904. this._physicsPlugin = _physicsPlugin;
  73905. //new methods and parameters
  73906. this._impostors = [];
  73907. this._joints = [];
  73908. if (!this._physicsPlugin.isSupported()) {
  73909. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  73910. + "Please make sure it is included.");
  73911. }
  73912. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  73913. this.setGravity(gravity);
  73914. this.setTimeStep();
  73915. }
  73916. PhysicsEngine.prototype.setGravity = function (gravity) {
  73917. this.gravity = gravity;
  73918. this._physicsPlugin.setGravity(this.gravity);
  73919. };
  73920. /**
  73921. * Set the time step of the physics engine.
  73922. * default is 1/60.
  73923. * To slow it down, enter 1/600 for example.
  73924. * To speed it up, 1/30
  73925. * @param {number} newTimeStep the new timestep to apply to this world.
  73926. */
  73927. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  73928. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  73929. this._physicsPlugin.setTimeStep(newTimeStep);
  73930. };
  73931. /**
  73932. * Get the time step of the physics engine.
  73933. */
  73934. PhysicsEngine.prototype.getTimeStep = function () {
  73935. return this._physicsPlugin.getTimeStep();
  73936. };
  73937. PhysicsEngine.prototype.dispose = function () {
  73938. this._impostors.forEach(function (impostor) {
  73939. impostor.dispose();
  73940. });
  73941. this._physicsPlugin.dispose();
  73942. };
  73943. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  73944. return this._physicsPlugin.name;
  73945. };
  73946. /**
  73947. * Adding a new impostor for the impostor tracking.
  73948. * This will be done by the impostor itself.
  73949. * @param {PhysicsImpostor} impostor the impostor to add
  73950. */
  73951. PhysicsEngine.prototype.addImpostor = function (impostor) {
  73952. impostor.uniqueId = this._impostors.push(impostor);
  73953. //if no parent, generate the body
  73954. if (!impostor.parent) {
  73955. this._physicsPlugin.generatePhysicsBody(impostor);
  73956. }
  73957. };
  73958. /**
  73959. * Remove an impostor from the engine.
  73960. * This impostor and its mesh will not longer be updated by the physics engine.
  73961. * @param {PhysicsImpostor} impostor the impostor to remove
  73962. */
  73963. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  73964. var index = this._impostors.indexOf(impostor);
  73965. if (index > -1) {
  73966. var removed = this._impostors.splice(index, 1);
  73967. //Is it needed?
  73968. if (removed.length) {
  73969. //this will also remove it from the world.
  73970. removed[0].physicsBody = null;
  73971. }
  73972. }
  73973. };
  73974. /**
  73975. * Add a joint to the physics engine
  73976. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  73977. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  73978. * @param {PhysicsJoint} the joint that will connect both impostors.
  73979. */
  73980. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  73981. var impostorJoint = {
  73982. mainImpostor: mainImpostor,
  73983. connectedImpostor: connectedImpostor,
  73984. joint: joint
  73985. };
  73986. joint.physicsPlugin = this._physicsPlugin;
  73987. this._joints.push(impostorJoint);
  73988. this._physicsPlugin.generateJoint(impostorJoint);
  73989. };
  73990. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  73991. var matchingJoints = this._joints.filter(function (impostorJoint) {
  73992. return (impostorJoint.connectedImpostor === connectedImpostor
  73993. && impostorJoint.joint === joint
  73994. && impostorJoint.mainImpostor === mainImpostor);
  73995. });
  73996. if (matchingJoints.length) {
  73997. this._physicsPlugin.removeJoint(matchingJoints[0]);
  73998. //TODO remove it from the list as well
  73999. }
  74000. };
  74001. /**
  74002. * Called by the scene. no need to call it.
  74003. */
  74004. PhysicsEngine.prototype._step = function (delta) {
  74005. var _this = this;
  74006. //check if any mesh has no body / requires an update
  74007. this._impostors.forEach(function (impostor) {
  74008. if (impostor.isBodyInitRequired()) {
  74009. _this._physicsPlugin.generatePhysicsBody(impostor);
  74010. }
  74011. });
  74012. if (delta > 0.1) {
  74013. delta = 0.1;
  74014. }
  74015. else if (delta <= 0) {
  74016. delta = 1.0 / 60.0;
  74017. }
  74018. this._physicsPlugin.executeStep(delta, this._impostors);
  74019. };
  74020. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  74021. return this._physicsPlugin;
  74022. };
  74023. PhysicsEngine.prototype.getImpostors = function () {
  74024. return this._impostors;
  74025. };
  74026. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  74027. for (var i = 0; i < this._impostors.length; ++i) {
  74028. if (this._impostors[i].object === object) {
  74029. return this._impostors[i];
  74030. }
  74031. }
  74032. return null;
  74033. };
  74034. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  74035. for (var i = 0; i < this._impostors.length; ++i) {
  74036. if (this._impostors[i].physicsBody === body) {
  74037. return this._impostors[i];
  74038. }
  74039. }
  74040. return null;
  74041. };
  74042. // Statics
  74043. PhysicsEngine.Epsilon = 0.001;
  74044. return PhysicsEngine;
  74045. }());
  74046. BABYLON.PhysicsEngine = PhysicsEngine;
  74047. })(BABYLON || (BABYLON = {}));
  74048. //# sourceMappingURL=babylon.physicsEngine.js.map
  74049. var BABYLON;
  74050. (function (BABYLON) {
  74051. var PhysicsHelper = /** @class */ (function () {
  74052. function PhysicsHelper(scene) {
  74053. this._scene = scene;
  74054. this._physicsEngine = this._scene.getPhysicsEngine();
  74055. if (!this._physicsEngine) {
  74056. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  74057. }
  74058. }
  74059. /**
  74060. * @param {Vector3} origin the origin of the explosion
  74061. * @param {number} radius the explosion radius
  74062. * @param {number} strength the explosion strength
  74063. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74064. */
  74065. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  74066. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74067. if (!this._physicsEngine) {
  74068. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  74069. return null;
  74070. }
  74071. var impostors = this._physicsEngine.getImpostors();
  74072. if (impostors.length === 0) {
  74073. return null;
  74074. }
  74075. var event = new PhysicsRadialExplosionEvent(this._scene);
  74076. impostors.forEach(function (impostor) {
  74077. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  74078. if (!impostorForceAndContactPoint) {
  74079. return;
  74080. }
  74081. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74082. });
  74083. event.dispose(false);
  74084. return event;
  74085. };
  74086. /**
  74087. * @param {Vector3} origin the origin of the explosion
  74088. * @param {number} radius the explosion radius
  74089. * @param {number} strength the explosion strength
  74090. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74091. */
  74092. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  74093. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74094. if (!this._physicsEngine) {
  74095. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74096. return null;
  74097. }
  74098. var impostors = this._physicsEngine.getImpostors();
  74099. if (impostors.length === 0) {
  74100. return null;
  74101. }
  74102. var event = new PhysicsRadialExplosionEvent(this._scene);
  74103. impostors.forEach(function (impostor) {
  74104. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  74105. if (!impostorForceAndContactPoint) {
  74106. return;
  74107. }
  74108. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74109. });
  74110. event.dispose(false);
  74111. return event;
  74112. };
  74113. /**
  74114. * @param {Vector3} origin the origin of the explosion
  74115. * @param {number} radius the explosion radius
  74116. * @param {number} strength the explosion strength
  74117. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74118. */
  74119. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  74120. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74121. if (!this._physicsEngine) {
  74122. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74123. return null;
  74124. }
  74125. var impostors = this._physicsEngine.getImpostors();
  74126. if (impostors.length === 0) {
  74127. return null;
  74128. }
  74129. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  74130. event.dispose(false);
  74131. return event;
  74132. };
  74133. /**
  74134. * @param {Vector3} origin the origin of the updraft
  74135. * @param {number} radius the radius of the updraft
  74136. * @param {number} strength the strength of the updraft
  74137. * @param {number} height the height of the updraft
  74138. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  74139. */
  74140. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  74141. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  74142. if (!this._physicsEngine) {
  74143. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74144. return null;
  74145. }
  74146. if (this._physicsEngine.getImpostors().length === 0) {
  74147. return null;
  74148. }
  74149. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  74150. event.dispose(false);
  74151. return event;
  74152. };
  74153. /**
  74154. * @param {Vector3} origin the of the vortex
  74155. * @param {number} radius the radius of the vortex
  74156. * @param {number} strength the strength of the vortex
  74157. * @param {number} height the height of the vortex
  74158. */
  74159. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  74160. if (!this._physicsEngine) {
  74161. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74162. return null;
  74163. }
  74164. if (this._physicsEngine.getImpostors().length === 0) {
  74165. return null;
  74166. }
  74167. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  74168. event.dispose(false);
  74169. return event;
  74170. };
  74171. return PhysicsHelper;
  74172. }());
  74173. BABYLON.PhysicsHelper = PhysicsHelper;
  74174. /***** Radial explosion *****/
  74175. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  74176. function PhysicsRadialExplosionEvent(scene) {
  74177. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  74178. this._rays = [];
  74179. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  74180. this._scene = scene;
  74181. }
  74182. /**
  74183. * Returns the data related to the radial explosion event (sphere & rays).
  74184. * @returns {PhysicsRadialExplosionEventData}
  74185. */
  74186. PhysicsRadialExplosionEvent.prototype.getData = function () {
  74187. this._dataFetched = true;
  74188. return {
  74189. sphere: this._sphere,
  74190. rays: this._rays,
  74191. };
  74192. };
  74193. /**
  74194. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  74195. * @param impostor
  74196. * @param {Vector3} origin the origin of the explosion
  74197. * @param {number} radius the explosion radius
  74198. * @param {number} strength the explosion strength
  74199. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  74200. * @returns {Nullable<PhysicsForceAndContactPoint>}
  74201. */
  74202. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  74203. if (impostor.mass === 0) {
  74204. return null;
  74205. }
  74206. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  74207. return null;
  74208. }
  74209. if (impostor.object.getClassName() !== 'Mesh') {
  74210. return null;
  74211. }
  74212. var impostorObject = impostor.object;
  74213. var impostorObjectCenter = impostor.getObjectCenter();
  74214. var direction = impostorObjectCenter.subtract(origin);
  74215. var ray = new BABYLON.Ray(origin, direction, radius);
  74216. this._rays.push(ray);
  74217. var hit = ray.intersectsMesh(impostorObject);
  74218. var contactPoint = hit.pickedPoint;
  74219. if (!contactPoint) {
  74220. return null;
  74221. }
  74222. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  74223. if (distanceFromOrigin > radius) {
  74224. return null;
  74225. }
  74226. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  74227. ? strength
  74228. : strength * (1 - (distanceFromOrigin / radius));
  74229. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74230. return { force: force, contactPoint: contactPoint };
  74231. };
  74232. /**
  74233. * Disposes the sphere.
  74234. * @param {bolean} force
  74235. */
  74236. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  74237. var _this = this;
  74238. if (force === void 0) { force = true; }
  74239. if (force) {
  74240. this._sphere.dispose();
  74241. }
  74242. else {
  74243. setTimeout(function () {
  74244. if (!_this._dataFetched) {
  74245. _this._sphere.dispose();
  74246. }
  74247. }, 0);
  74248. }
  74249. };
  74250. /*** Helpers ***/
  74251. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  74252. if (!this._sphere) {
  74253. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  74254. this._sphere.isVisible = false;
  74255. }
  74256. };
  74257. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  74258. var impostorObject = impostor.object;
  74259. this._prepareSphere();
  74260. this._sphere.position = origin;
  74261. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  74262. this._sphere._updateBoundingInfo();
  74263. this._sphere.computeWorldMatrix(true);
  74264. return this._sphere.intersectsMesh(impostorObject, true);
  74265. };
  74266. return PhysicsRadialExplosionEvent;
  74267. }());
  74268. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  74269. /***** Gravitational Field *****/
  74270. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  74271. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  74272. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74273. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74274. this._physicsHelper = physicsHelper;
  74275. this._scene = scene;
  74276. this._origin = origin;
  74277. this._radius = radius;
  74278. this._strength = strength;
  74279. this._falloff = falloff;
  74280. this._tickCallback = this._tick.bind(this);
  74281. }
  74282. /**
  74283. * Returns the data related to the gravitational field event (sphere).
  74284. * @returns {PhysicsGravitationalFieldEventData}
  74285. */
  74286. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  74287. this._dataFetched = true;
  74288. return {
  74289. sphere: this._sphere,
  74290. };
  74291. };
  74292. /**
  74293. * Enables the gravitational field.
  74294. */
  74295. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  74296. this._tickCallback.call(this);
  74297. this._scene.registerBeforeRender(this._tickCallback);
  74298. };
  74299. /**
  74300. * Disables the gravitational field.
  74301. */
  74302. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  74303. this._scene.unregisterBeforeRender(this._tickCallback);
  74304. };
  74305. /**
  74306. * Disposes the sphere.
  74307. * @param {bolean} force
  74308. */
  74309. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  74310. var _this = this;
  74311. if (force === void 0) { force = true; }
  74312. if (force) {
  74313. this._sphere.dispose();
  74314. }
  74315. else {
  74316. setTimeout(function () {
  74317. if (!_this._dataFetched) {
  74318. _this._sphere.dispose();
  74319. }
  74320. }, 0);
  74321. }
  74322. };
  74323. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  74324. // Since the params won't change, we fetch the event only once
  74325. if (this._sphere) {
  74326. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74327. }
  74328. else {
  74329. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74330. if (radialExplosionEvent) {
  74331. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  74332. }
  74333. }
  74334. };
  74335. return PhysicsGravitationalFieldEvent;
  74336. }());
  74337. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  74338. /***** Updraft *****/
  74339. var PhysicsUpdraftEvent = /** @class */ (function () {
  74340. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  74341. this._scene = _scene;
  74342. this._origin = _origin;
  74343. this._radius = _radius;
  74344. this._strength = _strength;
  74345. this._height = _height;
  74346. this._updraftMode = _updraftMode;
  74347. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74348. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  74349. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74350. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74351. this._physicsEngine = this._scene.getPhysicsEngine();
  74352. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74353. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74354. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74355. this._originDirection = this._origin.subtract(this._originTop).normalize();
  74356. }
  74357. this._tickCallback = this._tick.bind(this);
  74358. }
  74359. /**
  74360. * Returns the data related to the updraft event (cylinder).
  74361. * @returns {PhysicsUpdraftEventData}
  74362. */
  74363. PhysicsUpdraftEvent.prototype.getData = function () {
  74364. this._dataFetched = true;
  74365. return {
  74366. cylinder: this._cylinder,
  74367. };
  74368. };
  74369. /**
  74370. * Enables the updraft.
  74371. */
  74372. PhysicsUpdraftEvent.prototype.enable = function () {
  74373. this._tickCallback.call(this);
  74374. this._scene.registerBeforeRender(this._tickCallback);
  74375. };
  74376. /**
  74377. * Disables the cortex.
  74378. */
  74379. PhysicsUpdraftEvent.prototype.disable = function () {
  74380. this._scene.unregisterBeforeRender(this._tickCallback);
  74381. };
  74382. /**
  74383. * Disposes the sphere.
  74384. * @param {bolean} force
  74385. */
  74386. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  74387. var _this = this;
  74388. if (force === void 0) { force = true; }
  74389. if (force) {
  74390. this._cylinder.dispose();
  74391. }
  74392. else {
  74393. setTimeout(function () {
  74394. if (!_this._dataFetched) {
  74395. _this._cylinder.dispose();
  74396. }
  74397. }, 0);
  74398. }
  74399. };
  74400. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74401. if (impostor.mass === 0) {
  74402. return null;
  74403. }
  74404. if (!this._intersectsWithCylinder(impostor)) {
  74405. return null;
  74406. }
  74407. var impostorObjectCenter = impostor.getObjectCenter();
  74408. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74409. var direction = this._originDirection;
  74410. }
  74411. else {
  74412. var direction = impostorObjectCenter.subtract(this._originTop);
  74413. }
  74414. var multiplier = this._strength * -1;
  74415. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74416. return { force: force, contactPoint: impostorObjectCenter };
  74417. };
  74418. PhysicsUpdraftEvent.prototype._tick = function () {
  74419. var _this = this;
  74420. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74421. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74422. if (!impostorForceAndContactPoint) {
  74423. return;
  74424. }
  74425. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74426. });
  74427. };
  74428. /*** Helpers ***/
  74429. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  74430. if (!this._cylinder) {
  74431. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  74432. height: this._height,
  74433. diameter: this._radius * 2,
  74434. }, this._scene);
  74435. this._cylinder.isVisible = false;
  74436. }
  74437. };
  74438. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  74439. var impostorObject = impostor.object;
  74440. this._prepareCylinder();
  74441. this._cylinder.position = this._cylinderPosition;
  74442. return this._cylinder.intersectsMesh(impostorObject, true);
  74443. };
  74444. return PhysicsUpdraftEvent;
  74445. }());
  74446. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  74447. /***** Vortex *****/
  74448. var PhysicsVortexEvent = /** @class */ (function () {
  74449. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  74450. this._scene = _scene;
  74451. this._origin = _origin;
  74452. this._radius = _radius;
  74453. this._strength = _strength;
  74454. this._height = _height;
  74455. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74456. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  74457. this._updraftMultiplier = 0.02;
  74458. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74459. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74460. this._physicsEngine = this._scene.getPhysicsEngine();
  74461. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74462. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74463. this._tickCallback = this._tick.bind(this);
  74464. }
  74465. /**
  74466. * Returns the data related to the vortex event (cylinder).
  74467. * @returns {PhysicsVortexEventData}
  74468. */
  74469. PhysicsVortexEvent.prototype.getData = function () {
  74470. this._dataFetched = true;
  74471. return {
  74472. cylinder: this._cylinder,
  74473. };
  74474. };
  74475. /**
  74476. * Enables the vortex.
  74477. */
  74478. PhysicsVortexEvent.prototype.enable = function () {
  74479. this._tickCallback.call(this);
  74480. this._scene.registerBeforeRender(this._tickCallback);
  74481. };
  74482. /**
  74483. * Disables the cortex.
  74484. */
  74485. PhysicsVortexEvent.prototype.disable = function () {
  74486. this._scene.unregisterBeforeRender(this._tickCallback);
  74487. };
  74488. /**
  74489. * Disposes the sphere.
  74490. * @param {bolean} force
  74491. */
  74492. PhysicsVortexEvent.prototype.dispose = function (force) {
  74493. var _this = this;
  74494. if (force === void 0) { force = true; }
  74495. if (force) {
  74496. this._cylinder.dispose();
  74497. }
  74498. else {
  74499. setTimeout(function () {
  74500. if (!_this._dataFetched) {
  74501. _this._cylinder.dispose();
  74502. }
  74503. }, 0);
  74504. }
  74505. };
  74506. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74507. if (impostor.mass === 0) {
  74508. return null;
  74509. }
  74510. if (!this._intersectsWithCylinder(impostor)) {
  74511. return null;
  74512. }
  74513. if (impostor.object.getClassName() !== 'Mesh') {
  74514. return null;
  74515. }
  74516. var impostorObject = impostor.object;
  74517. var impostorObjectCenter = impostor.getObjectCenter();
  74518. 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)
  74519. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  74520. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  74521. var hit = ray.intersectsMesh(impostorObject);
  74522. var contactPoint = hit.pickedPoint;
  74523. if (!contactPoint) {
  74524. return null;
  74525. }
  74526. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  74527. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  74528. var directionToOrigin = contactPoint.normalize();
  74529. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74530. directionToOrigin = directionToOrigin.negate();
  74531. }
  74532. // TODO: find a more physically based solution
  74533. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74534. var forceX = directionToOrigin.x * this._strength / 8;
  74535. var forceY = directionToOrigin.y * this._updraftMultiplier;
  74536. var forceZ = directionToOrigin.z * this._strength / 8;
  74537. }
  74538. else {
  74539. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  74540. var forceY = this._originTop.y * this._updraftMultiplier;
  74541. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  74542. }
  74543. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  74544. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  74545. return { force: force, contactPoint: impostorObjectCenter };
  74546. };
  74547. PhysicsVortexEvent.prototype._tick = function () {
  74548. var _this = this;
  74549. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74550. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74551. if (!impostorForceAndContactPoint) {
  74552. return;
  74553. }
  74554. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74555. });
  74556. };
  74557. /*** Helpers ***/
  74558. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  74559. if (!this._cylinder) {
  74560. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  74561. height: this._height,
  74562. diameter: this._radius * 2,
  74563. }, this._scene);
  74564. this._cylinder.isVisible = false;
  74565. }
  74566. };
  74567. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  74568. var impostorObject = impostor.object;
  74569. this._prepareCylinder();
  74570. this._cylinder.position = this._cylinderPosition;
  74571. return this._cylinder.intersectsMesh(impostorObject, true);
  74572. };
  74573. return PhysicsVortexEvent;
  74574. }());
  74575. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  74576. /***** Enums *****/
  74577. /**
  74578. * The strenght of the force in correspondence to the distance of the affected object
  74579. */
  74580. var PhysicsRadialImpulseFalloff;
  74581. (function (PhysicsRadialImpulseFalloff) {
  74582. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  74583. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  74584. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  74585. /**
  74586. * The strenght of the force in correspondence to the distance of the affected object
  74587. */
  74588. var PhysicsUpdraftMode;
  74589. (function (PhysicsUpdraftMode) {
  74590. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  74591. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  74592. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  74593. })(BABYLON || (BABYLON = {}));
  74594. //# sourceMappingURL=babylon.physicsHelper.js.map
  74595. var BABYLON;
  74596. (function (BABYLON) {
  74597. var CannonJSPlugin = /** @class */ (function () {
  74598. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  74599. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  74600. if (iterations === void 0) { iterations = 10; }
  74601. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  74602. this.name = "CannonJSPlugin";
  74603. this._physicsMaterials = new Array();
  74604. this._fixedTimeStep = 1 / 60;
  74605. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  74606. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  74607. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  74608. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  74609. this._tmpPosition = BABYLON.Vector3.Zero();
  74610. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  74611. this._tmpUnityRotation = new BABYLON.Quaternion();
  74612. if (!this.isSupported()) {
  74613. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  74614. return;
  74615. }
  74616. this._extendNamespace();
  74617. this.world = new this.BJSCANNON.World();
  74618. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  74619. this.world.solver.iterations = iterations;
  74620. }
  74621. CannonJSPlugin.prototype.setGravity = function (gravity) {
  74622. this.world.gravity.copy(gravity);
  74623. };
  74624. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  74625. this._fixedTimeStep = timeStep;
  74626. };
  74627. CannonJSPlugin.prototype.getTimeStep = function () {
  74628. return this._fixedTimeStep;
  74629. };
  74630. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  74631. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  74632. };
  74633. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  74634. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74635. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74636. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  74637. };
  74638. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  74639. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74640. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74641. impostor.physicsBody.applyForce(impulse, worldPoint);
  74642. };
  74643. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  74644. //parent-child relationship. Does this impostor has a parent impostor?
  74645. if (impostor.parent) {
  74646. if (impostor.physicsBody) {
  74647. this.removePhysicsBody(impostor);
  74648. //TODO is that needed?
  74649. impostor.forceUpdate();
  74650. }
  74651. return;
  74652. }
  74653. //should a new body be created for this impostor?
  74654. if (impostor.isBodyInitRequired()) {
  74655. var shape = this._createShape(impostor);
  74656. //unregister events, if body is being changed
  74657. var oldBody = impostor.physicsBody;
  74658. if (oldBody) {
  74659. this.removePhysicsBody(impostor);
  74660. }
  74661. //create the body and material
  74662. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  74663. var bodyCreationObject = {
  74664. mass: impostor.getParam("mass"),
  74665. material: material
  74666. };
  74667. // A simple extend, in case native options were used.
  74668. var nativeOptions = impostor.getParam("nativeOptions");
  74669. for (var key in nativeOptions) {
  74670. if (nativeOptions.hasOwnProperty(key)) {
  74671. bodyCreationObject[key] = nativeOptions[key];
  74672. }
  74673. }
  74674. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  74675. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  74676. this.world.addEventListener("preStep", impostor.beforeStep);
  74677. this.world.addEventListener("postStep", impostor.afterStep);
  74678. impostor.physicsBody.addShape(shape);
  74679. this.world.add(impostor.physicsBody);
  74680. //try to keep the body moving in the right direction by taking old properties.
  74681. //Should be tested!
  74682. if (oldBody) {
  74683. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  74684. impostor.physicsBody[param].copy(oldBody[param]);
  74685. });
  74686. }
  74687. this._processChildMeshes(impostor);
  74688. }
  74689. //now update the body's transformation
  74690. this._updatePhysicsBodyTransformation(impostor);
  74691. };
  74692. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  74693. var _this = this;
  74694. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  74695. var currentRotation = mainImpostor.object.rotationQuaternion;
  74696. if (meshChildren.length) {
  74697. var processMesh = function (localPosition, mesh) {
  74698. if (!currentRotation || !mesh.rotationQuaternion) {
  74699. return;
  74700. }
  74701. var childImpostor = mesh.getPhysicsImpostor();
  74702. if (childImpostor) {
  74703. var parent = childImpostor.parent;
  74704. if (parent !== mainImpostor) {
  74705. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  74706. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  74707. if (childImpostor.physicsBody) {
  74708. _this.removePhysicsBody(childImpostor);
  74709. childImpostor.physicsBody = null;
  74710. }
  74711. childImpostor.parent = mainImpostor;
  74712. childImpostor.resetUpdateFlags();
  74713. 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));
  74714. //Add the mass of the children.
  74715. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  74716. }
  74717. }
  74718. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  74719. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  74720. };
  74721. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  74722. }
  74723. };
  74724. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  74725. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  74726. this.world.removeEventListener("preStep", impostor.beforeStep);
  74727. this.world.removeEventListener("postStep", impostor.afterStep);
  74728. this.world.remove(impostor.physicsBody);
  74729. };
  74730. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  74731. var mainBody = impostorJoint.mainImpostor.physicsBody;
  74732. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  74733. if (!mainBody || !connectedBody) {
  74734. return;
  74735. }
  74736. var constraint;
  74737. var jointData = impostorJoint.joint.jointData;
  74738. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  74739. var constraintData = {
  74740. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  74741. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  74742. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  74743. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  74744. maxForce: jointData.nativeParams.maxForce,
  74745. collideConnected: !!jointData.collision
  74746. };
  74747. switch (impostorJoint.joint.type) {
  74748. case BABYLON.PhysicsJoint.HingeJoint:
  74749. case BABYLON.PhysicsJoint.Hinge2Joint:
  74750. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  74751. break;
  74752. case BABYLON.PhysicsJoint.DistanceJoint:
  74753. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  74754. break;
  74755. case BABYLON.PhysicsJoint.SpringJoint:
  74756. var springData = jointData;
  74757. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  74758. restLength: springData.length,
  74759. stiffness: springData.stiffness,
  74760. damping: springData.damping,
  74761. localAnchorA: constraintData.pivotA,
  74762. localAnchorB: constraintData.pivotB
  74763. });
  74764. break;
  74765. case BABYLON.PhysicsJoint.LockJoint:
  74766. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  74767. break;
  74768. case BABYLON.PhysicsJoint.PointToPointJoint:
  74769. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  74770. default:
  74771. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  74772. break;
  74773. }
  74774. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  74775. constraint.collideConnected = !!jointData.collision;
  74776. impostorJoint.joint.physicsJoint = constraint;
  74777. //don't add spring as constraint, as it is not one.
  74778. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  74779. this.world.addConstraint(constraint);
  74780. }
  74781. else {
  74782. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  74783. constraint.applyForce();
  74784. });
  74785. }
  74786. };
  74787. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  74788. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  74789. };
  74790. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  74791. var index;
  74792. var mat;
  74793. for (index = 0; index < this._physicsMaterials.length; index++) {
  74794. mat = this._physicsMaterials[index];
  74795. if (mat.friction === friction && mat.restitution === restitution) {
  74796. return mat;
  74797. }
  74798. }
  74799. var currentMat = new this.BJSCANNON.Material(name);
  74800. currentMat.friction = friction;
  74801. currentMat.restitution = restitution;
  74802. this._physicsMaterials.push(currentMat);
  74803. return currentMat;
  74804. };
  74805. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  74806. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  74807. };
  74808. CannonJSPlugin.prototype._createShape = function (impostor) {
  74809. var object = impostor.object;
  74810. var returnValue;
  74811. var extendSize = impostor.getObjectExtendSize();
  74812. switch (impostor.type) {
  74813. case BABYLON.PhysicsImpostor.SphereImpostor:
  74814. var radiusX = extendSize.x;
  74815. var radiusY = extendSize.y;
  74816. var radiusZ = extendSize.z;
  74817. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  74818. break;
  74819. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  74820. case BABYLON.PhysicsImpostor.CylinderImpostor:
  74821. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  74822. break;
  74823. case BABYLON.PhysicsImpostor.BoxImpostor:
  74824. var box = extendSize.scale(0.5);
  74825. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  74826. break;
  74827. case BABYLON.PhysicsImpostor.PlaneImpostor:
  74828. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  74829. returnValue = new this.BJSCANNON.Plane();
  74830. break;
  74831. case BABYLON.PhysicsImpostor.MeshImpostor:
  74832. // should transform the vertex data to world coordinates!!
  74833. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  74834. var rawFaces = object.getIndices ? object.getIndices() : [];
  74835. if (!rawVerts)
  74836. return;
  74837. // get only scale! so the object could transform correctly.
  74838. var oldPosition = object.position.clone();
  74839. var oldRotation = object.rotation && object.rotation.clone();
  74840. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  74841. object.position.copyFromFloats(0, 0, 0);
  74842. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74843. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74844. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74845. var transform = object.computeWorldMatrix(true);
  74846. // convert rawVerts to object space
  74847. var temp = new Array();
  74848. var index;
  74849. for (index = 0; index < rawVerts.length; index += 3) {
  74850. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  74851. }
  74852. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  74853. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  74854. //now set back the transformation!
  74855. object.position.copyFrom(oldPosition);
  74856. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  74857. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  74858. break;
  74859. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  74860. var oldPosition2 = object.position.clone();
  74861. var oldRotation2 = object.rotation && object.rotation.clone();
  74862. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  74863. object.position.copyFromFloats(0, 0, 0);
  74864. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74865. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74866. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74867. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  74868. returnValue = this._createHeightmap(object);
  74869. object.position.copyFrom(oldPosition2);
  74870. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  74871. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  74872. object.computeWorldMatrix(true);
  74873. break;
  74874. case BABYLON.PhysicsImpostor.ParticleImpostor:
  74875. returnValue = new this.BJSCANNON.Particle();
  74876. break;
  74877. }
  74878. return returnValue;
  74879. };
  74880. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  74881. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  74882. var transform = object.computeWorldMatrix(true);
  74883. // convert rawVerts to object space
  74884. var temp = new Array();
  74885. var index;
  74886. for (index = 0; index < pos.length; index += 3) {
  74887. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  74888. }
  74889. pos = temp;
  74890. var matrix = new Array();
  74891. //For now pointDepth will not be used and will be automatically calculated.
  74892. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  74893. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  74894. var boundingInfo = object.getBoundingInfo();
  74895. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  74896. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  74897. var elementSize = dim * 2 / arraySize;
  74898. for (var i = 0; i < pos.length; i = i + 3) {
  74899. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  74900. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  74901. var y = -pos[i + 2] + minY;
  74902. if (!matrix[x]) {
  74903. matrix[x] = [];
  74904. }
  74905. if (!matrix[x][z]) {
  74906. matrix[x][z] = y;
  74907. }
  74908. matrix[x][z] = Math.max(y, matrix[x][z]);
  74909. }
  74910. for (var x = 0; x <= arraySize; ++x) {
  74911. if (!matrix[x]) {
  74912. var loc = 1;
  74913. while (!matrix[(x + loc) % arraySize]) {
  74914. loc++;
  74915. }
  74916. matrix[x] = matrix[(x + loc) % arraySize].slice();
  74917. //console.log("missing x", x);
  74918. }
  74919. for (var z = 0; z <= arraySize; ++z) {
  74920. if (!matrix[x][z]) {
  74921. var loc = 1;
  74922. var newValue;
  74923. while (newValue === undefined) {
  74924. newValue = matrix[x][(z + loc++) % arraySize];
  74925. }
  74926. matrix[x][z] = newValue;
  74927. }
  74928. }
  74929. }
  74930. var shape = new this.BJSCANNON.Heightfield(matrix, {
  74931. elementSize: elementSize
  74932. });
  74933. //For future reference, needed for body transformation
  74934. shape.minY = minY;
  74935. return shape;
  74936. };
  74937. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  74938. var object = impostor.object;
  74939. //make sure it is updated...
  74940. object.computeWorldMatrix && object.computeWorldMatrix(true);
  74941. // The delta between the mesh position and the mesh bounding box center
  74942. var bInfo = object.getBoundingInfo();
  74943. if (!bInfo)
  74944. return;
  74945. var center = impostor.getObjectCenter();
  74946. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  74947. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  74948. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  74949. this._tmpPosition.copyFrom(center);
  74950. var quaternion = object.rotationQuaternion;
  74951. if (!quaternion) {
  74952. return;
  74953. }
  74954. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  74955. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  74956. //-90 DEG in X, precalculated
  74957. quaternion = quaternion.multiply(this._minus90X);
  74958. //Invert! (Precalculated, 90 deg in X)
  74959. //No need to clone. this will never change.
  74960. impostor.setDeltaRotation(this._plus90X);
  74961. }
  74962. //If it is a heightfield, if should be centered.
  74963. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  74964. var mesh = object;
  74965. var boundingInfo = mesh.getBoundingInfo();
  74966. //calculate the correct body position:
  74967. var rotationQuaternion = mesh.rotationQuaternion;
  74968. mesh.rotationQuaternion = this._tmpUnityRotation;
  74969. mesh.computeWorldMatrix(true);
  74970. //get original center with no rotation
  74971. var c = center.clone();
  74972. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  74973. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  74974. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  74975. mesh.setPreTransformMatrix(p);
  74976. mesh.computeWorldMatrix(true);
  74977. //calculate the translation
  74978. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  74979. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  74980. //add it inverted to the delta
  74981. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  74982. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  74983. //rotation is back
  74984. mesh.rotationQuaternion = rotationQuaternion;
  74985. mesh.setPreTransformMatrix(oldPivot);
  74986. mesh.computeWorldMatrix(true);
  74987. }
  74988. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  74989. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  74990. //this._tmpPosition.copyFrom(object.position);
  74991. }
  74992. impostor.setDeltaPosition(this._tmpDeltaPosition);
  74993. //Now update the impostor object
  74994. impostor.physicsBody.position.copy(this._tmpPosition);
  74995. impostor.physicsBody.quaternion.copy(quaternion);
  74996. };
  74997. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  74998. impostor.object.position.copyFrom(impostor.physicsBody.position);
  74999. if (impostor.object.rotationQuaternion) {
  75000. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  75001. }
  75002. };
  75003. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75004. impostor.physicsBody.position.copy(newPosition);
  75005. impostor.physicsBody.quaternion.copy(newRotation);
  75006. };
  75007. CannonJSPlugin.prototype.isSupported = function () {
  75008. return this.BJSCANNON !== undefined;
  75009. };
  75010. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75011. impostor.physicsBody.velocity.copy(velocity);
  75012. };
  75013. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75014. impostor.physicsBody.angularVelocity.copy(velocity);
  75015. };
  75016. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75017. var v = impostor.physicsBody.velocity;
  75018. if (!v) {
  75019. return null;
  75020. }
  75021. return new BABYLON.Vector3(v.x, v.y, v.z);
  75022. };
  75023. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75024. var v = impostor.physicsBody.angularVelocity;
  75025. if (!v) {
  75026. return null;
  75027. }
  75028. return new BABYLON.Vector3(v.x, v.y, v.z);
  75029. };
  75030. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75031. impostor.physicsBody.mass = mass;
  75032. impostor.physicsBody.updateMassProperties();
  75033. };
  75034. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  75035. return impostor.physicsBody.mass;
  75036. };
  75037. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  75038. return impostor.physicsBody.material.friction;
  75039. };
  75040. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75041. impostor.physicsBody.material.friction = friction;
  75042. };
  75043. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75044. return impostor.physicsBody.material.restitution;
  75045. };
  75046. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75047. impostor.physicsBody.material.restitution = restitution;
  75048. };
  75049. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  75050. impostor.physicsBody.sleep();
  75051. };
  75052. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  75053. impostor.physicsBody.wakeUp();
  75054. };
  75055. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75056. joint.physicsJoint.distance = maxDistance;
  75057. };
  75058. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  75059. // if (!motorIndex) {
  75060. // joint.physicsJoint.enableMotor();
  75061. // }
  75062. // }
  75063. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  75064. // if (!motorIndex) {
  75065. // joint.physicsJoint.disableMotor();
  75066. // }
  75067. // }
  75068. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75069. if (!motorIndex) {
  75070. joint.physicsJoint.enableMotor();
  75071. joint.physicsJoint.setMotorSpeed(speed);
  75072. if (maxForce) {
  75073. this.setLimit(joint, maxForce);
  75074. }
  75075. }
  75076. };
  75077. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  75078. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  75079. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  75080. };
  75081. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75082. var body = impostor.physicsBody;
  75083. mesh.position.x = body.position.x;
  75084. mesh.position.y = body.position.y;
  75085. mesh.position.z = body.position.z;
  75086. if (mesh.rotationQuaternion) {
  75087. mesh.rotationQuaternion.x = body.quaternion.x;
  75088. mesh.rotationQuaternion.y = body.quaternion.y;
  75089. mesh.rotationQuaternion.z = body.quaternion.z;
  75090. mesh.rotationQuaternion.w = body.quaternion.w;
  75091. }
  75092. };
  75093. CannonJSPlugin.prototype.getRadius = function (impostor) {
  75094. var shape = impostor.physicsBody.shapes[0];
  75095. return shape.boundingSphereRadius;
  75096. };
  75097. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75098. var shape = impostor.physicsBody.shapes[0];
  75099. result.x = shape.halfExtents.x * 2;
  75100. result.y = shape.halfExtents.y * 2;
  75101. result.z = shape.halfExtents.z * 2;
  75102. };
  75103. CannonJSPlugin.prototype.dispose = function () {
  75104. };
  75105. CannonJSPlugin.prototype._extendNamespace = function () {
  75106. //this will force cannon to execute at least one step when using interpolation
  75107. var step_tmp1 = new this.BJSCANNON.Vec3();
  75108. var Engine = this.BJSCANNON;
  75109. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  75110. maxSubSteps = maxSubSteps || 10;
  75111. timeSinceLastCalled = timeSinceLastCalled || 0;
  75112. if (timeSinceLastCalled === 0) {
  75113. this.internalStep(dt);
  75114. this.time += dt;
  75115. }
  75116. else {
  75117. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  75118. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  75119. var t0 = performance.now();
  75120. for (var i = 0; i !== internalSteps; i++) {
  75121. this.internalStep(dt);
  75122. if (performance.now() - t0 > dt * 1000) {
  75123. break;
  75124. }
  75125. }
  75126. this.time += timeSinceLastCalled;
  75127. var h = this.time % dt;
  75128. var h_div_dt = h / dt;
  75129. var interpvelo = step_tmp1;
  75130. var bodies = this.bodies;
  75131. for (var j = 0; j !== bodies.length; j++) {
  75132. var b = bodies[j];
  75133. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  75134. b.position.vsub(b.previousPosition, interpvelo);
  75135. interpvelo.scale(h_div_dt, interpvelo);
  75136. b.position.vadd(interpvelo, b.interpolatedPosition);
  75137. }
  75138. else {
  75139. b.interpolatedPosition.copy(b.position);
  75140. b.interpolatedQuaternion.copy(b.quaternion);
  75141. }
  75142. }
  75143. }
  75144. };
  75145. };
  75146. return CannonJSPlugin;
  75147. }());
  75148. BABYLON.CannonJSPlugin = CannonJSPlugin;
  75149. })(BABYLON || (BABYLON = {}));
  75150. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  75151. var BABYLON;
  75152. (function (BABYLON) {
  75153. var OimoJSPlugin = /** @class */ (function () {
  75154. function OimoJSPlugin(iterations) {
  75155. this.name = "OimoJSPlugin";
  75156. this._tmpImpostorsArray = [];
  75157. this._tmpPositionVector = BABYLON.Vector3.Zero();
  75158. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  75159. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  75160. this.world.worldscale(1);
  75161. this.world.clear();
  75162. //making sure no stats are calculated
  75163. this.world.isNoStat = true;
  75164. }
  75165. OimoJSPlugin.prototype.setGravity = function (gravity) {
  75166. this.world.gravity.copy(gravity);
  75167. };
  75168. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  75169. this.world.timeStep = timeStep;
  75170. };
  75171. OimoJSPlugin.prototype.getTimeStep = function () {
  75172. return this.world.timeStep;
  75173. };
  75174. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  75175. var _this = this;
  75176. impostors.forEach(function (impostor) {
  75177. impostor.beforeStep();
  75178. });
  75179. this.world.step();
  75180. impostors.forEach(function (impostor) {
  75181. impostor.afterStep();
  75182. //update the ordered impostors array
  75183. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  75184. });
  75185. //check for collisions
  75186. var contact = this.world.contacts;
  75187. while (contact !== null) {
  75188. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  75189. contact = contact.next;
  75190. continue;
  75191. }
  75192. //is this body colliding with any other? get the impostor
  75193. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  75194. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  75195. if (!mainImpostor || !collidingImpostor) {
  75196. contact = contact.next;
  75197. continue;
  75198. }
  75199. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  75200. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  75201. contact = contact.next;
  75202. }
  75203. };
  75204. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75205. var mass = impostor.physicsBody.massInfo.mass;
  75206. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  75207. };
  75208. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75209. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  75210. this.applyImpulse(impostor, force, contactPoint);
  75211. };
  75212. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75213. var _this = this;
  75214. //parent-child relationship. Does this impostor has a parent impostor?
  75215. if (impostor.parent) {
  75216. if (impostor.physicsBody) {
  75217. this.removePhysicsBody(impostor);
  75218. //TODO is that needed?
  75219. impostor.forceUpdate();
  75220. }
  75221. return;
  75222. }
  75223. if (impostor.isBodyInitRequired()) {
  75224. var bodyConfig = {
  75225. name: impostor.uniqueId,
  75226. //Oimo must have mass, also for static objects.
  75227. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  75228. size: [],
  75229. type: [],
  75230. pos: [],
  75231. rot: [],
  75232. move: impostor.getParam("mass") !== 0,
  75233. //Supporting older versions of Oimo
  75234. world: this.world
  75235. };
  75236. var impostors = [impostor];
  75237. var addToArray = function (parent) {
  75238. if (!parent.getChildMeshes)
  75239. return;
  75240. parent.getChildMeshes().forEach(function (m) {
  75241. if (m.physicsImpostor) {
  75242. impostors.push(m.physicsImpostor);
  75243. //m.physicsImpostor._init();
  75244. }
  75245. });
  75246. };
  75247. addToArray(impostor.object);
  75248. var checkWithEpsilon_1 = function (value) {
  75249. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  75250. };
  75251. impostors.forEach(function (i) {
  75252. if (!impostor.object.rotationQuaternion) {
  75253. return;
  75254. }
  75255. //get the correct bounding box
  75256. var oldQuaternion = i.object.rotationQuaternion;
  75257. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  75258. x: impostor.object.rotationQuaternion.x,
  75259. y: impostor.object.rotationQuaternion.y,
  75260. z: impostor.object.rotationQuaternion.z,
  75261. s: impostor.object.rotationQuaternion.w
  75262. });
  75263. var extendSize = i.getObjectExtendSize();
  75264. if (i === impostor) {
  75265. var center = impostor.getObjectCenter();
  75266. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  75267. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  75268. //Can also use Array.prototype.push.apply
  75269. bodyConfig.pos.push(center.x);
  75270. bodyConfig.pos.push(center.y);
  75271. bodyConfig.pos.push(center.z);
  75272. //tmp solution
  75273. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75274. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75275. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75276. }
  75277. else {
  75278. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  75279. bodyConfig.pos.push(localPosition.x);
  75280. bodyConfig.pos.push(localPosition.y);
  75281. bodyConfig.pos.push(localPosition.z);
  75282. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  75283. bodyConfig.rot.push(0);
  75284. bodyConfig.rot.push(0);
  75285. bodyConfig.rot.push(0);
  75286. }
  75287. // register mesh
  75288. switch (i.type) {
  75289. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75290. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  75291. case BABYLON.PhysicsImpostor.SphereImpostor:
  75292. var radiusX = extendSize.x;
  75293. var radiusY = extendSize.y;
  75294. var radiusZ = extendSize.z;
  75295. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  75296. bodyConfig.type.push('sphere');
  75297. //due to the way oimo works with compounds, add 3 times
  75298. bodyConfig.size.push(size);
  75299. bodyConfig.size.push(size);
  75300. bodyConfig.size.push(size);
  75301. break;
  75302. case BABYLON.PhysicsImpostor.CylinderImpostor:
  75303. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  75304. var sizeY = checkWithEpsilon_1(extendSize.y);
  75305. bodyConfig.type.push('cylinder');
  75306. bodyConfig.size.push(sizeX);
  75307. bodyConfig.size.push(sizeY);
  75308. //due to the way oimo works with compounds, add one more value.
  75309. bodyConfig.size.push(sizeY);
  75310. break;
  75311. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75312. case BABYLON.PhysicsImpostor.BoxImpostor:
  75313. default:
  75314. var sizeX = checkWithEpsilon_1(extendSize.x);
  75315. var sizeY = checkWithEpsilon_1(extendSize.y);
  75316. var sizeZ = checkWithEpsilon_1(extendSize.z);
  75317. bodyConfig.type.push('box');
  75318. bodyConfig.size.push(sizeX);
  75319. bodyConfig.size.push(sizeY);
  75320. bodyConfig.size.push(sizeZ);
  75321. break;
  75322. }
  75323. //actually not needed, but hey...
  75324. i.object.rotationQuaternion = oldQuaternion;
  75325. });
  75326. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  75327. }
  75328. else {
  75329. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  75330. }
  75331. impostor.setDeltaPosition(this._tmpPositionVector);
  75332. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  75333. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  75334. };
  75335. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75336. //impostor.physicsBody.dispose();
  75337. //Same as : (older oimo versions)
  75338. this.world.removeRigidBody(impostor.physicsBody);
  75339. };
  75340. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75341. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75342. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75343. if (!mainBody || !connectedBody) {
  75344. return;
  75345. }
  75346. var jointData = impostorJoint.joint.jointData;
  75347. var options = jointData.nativeParams || {};
  75348. var type;
  75349. var nativeJointData = {
  75350. body1: mainBody,
  75351. body2: connectedBody,
  75352. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  75353. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  75354. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  75355. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  75356. min: options.min,
  75357. max: options.max,
  75358. collision: options.collision || jointData.collision,
  75359. spring: options.spring,
  75360. //supporting older version of Oimo
  75361. world: this.world
  75362. };
  75363. switch (impostorJoint.joint.type) {
  75364. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75365. type = "jointBall";
  75366. break;
  75367. case BABYLON.PhysicsJoint.SpringJoint:
  75368. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  75369. var springData = jointData;
  75370. nativeJointData.min = springData.length || nativeJointData.min;
  75371. //Max should also be set, just make sure it is at least min
  75372. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  75373. case BABYLON.PhysicsJoint.DistanceJoint:
  75374. type = "jointDistance";
  75375. nativeJointData.max = jointData.maxDistance;
  75376. break;
  75377. case BABYLON.PhysicsJoint.PrismaticJoint:
  75378. type = "jointPrisme";
  75379. break;
  75380. case BABYLON.PhysicsJoint.SliderJoint:
  75381. type = "jointSlide";
  75382. break;
  75383. case BABYLON.PhysicsJoint.WheelJoint:
  75384. type = "jointWheel";
  75385. break;
  75386. case BABYLON.PhysicsJoint.HingeJoint:
  75387. default:
  75388. type = "jointHinge";
  75389. break;
  75390. }
  75391. nativeJointData.type = type;
  75392. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  75393. };
  75394. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75395. //Bug in Oimo prevents us from disposing a joint in the playground
  75396. //joint.joint.physicsJoint.dispose();
  75397. //So we will bruteforce it!
  75398. try {
  75399. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  75400. }
  75401. catch (e) {
  75402. BABYLON.Tools.Warn(e);
  75403. }
  75404. };
  75405. OimoJSPlugin.prototype.isSupported = function () {
  75406. return this.BJSOIMO !== undefined;
  75407. };
  75408. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75409. if (!impostor.physicsBody.sleeping) {
  75410. //TODO check that
  75411. if (impostor.physicsBody.shapes.next) {
  75412. var parentShape = this._getLastShape(impostor.physicsBody);
  75413. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  75414. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  75415. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  75416. }
  75417. else {
  75418. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  75419. }
  75420. if (impostor.object.rotationQuaternion) {
  75421. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  75422. impostor.object.rotationQuaternion.normalize();
  75423. }
  75424. }
  75425. };
  75426. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75427. var body = impostor.physicsBody;
  75428. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  75429. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  75430. body.syncShapes();
  75431. body.awake();
  75432. };
  75433. OimoJSPlugin.prototype._getLastShape = function (body) {
  75434. var lastShape = body.shapes;
  75435. while (lastShape.next) {
  75436. lastShape = lastShape.next;
  75437. }
  75438. return lastShape;
  75439. };
  75440. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75441. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  75442. };
  75443. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75444. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  75445. };
  75446. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75447. var v = impostor.physicsBody.linearVelocity;
  75448. if (!v) {
  75449. return null;
  75450. }
  75451. return new BABYLON.Vector3(v.x, v.y, v.z);
  75452. };
  75453. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75454. var v = impostor.physicsBody.angularVelocity;
  75455. if (!v) {
  75456. return null;
  75457. }
  75458. return new BABYLON.Vector3(v.x, v.y, v.z);
  75459. };
  75460. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75461. var staticBody = mass === 0;
  75462. //this will actually set the body's density and not its mass.
  75463. //But this is how oimo treats the mass variable.
  75464. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  75465. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  75466. };
  75467. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  75468. return impostor.physicsBody.shapes.density;
  75469. };
  75470. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  75471. return impostor.physicsBody.shapes.friction;
  75472. };
  75473. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75474. impostor.physicsBody.shapes.friction = friction;
  75475. };
  75476. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75477. return impostor.physicsBody.shapes.restitution;
  75478. };
  75479. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75480. impostor.physicsBody.shapes.restitution = restitution;
  75481. };
  75482. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  75483. impostor.physicsBody.sleep();
  75484. };
  75485. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  75486. impostor.physicsBody.awake();
  75487. };
  75488. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75489. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  75490. if (minDistance !== void 0) {
  75491. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  75492. }
  75493. };
  75494. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75495. //TODO separate rotational and transational motors.
  75496. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75497. if (motor) {
  75498. motor.setMotor(speed, maxForce);
  75499. }
  75500. };
  75501. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  75502. //TODO separate rotational and transational motors.
  75503. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75504. if (motor) {
  75505. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  75506. }
  75507. };
  75508. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75509. var body = impostor.physicsBody;
  75510. mesh.position.x = body.position.x;
  75511. mesh.position.y = body.position.y;
  75512. mesh.position.z = body.position.z;
  75513. if (mesh.rotationQuaternion) {
  75514. mesh.rotationQuaternion.x = body.orientation.x;
  75515. mesh.rotationQuaternion.y = body.orientation.y;
  75516. mesh.rotationQuaternion.z = body.orientation.z;
  75517. mesh.rotationQuaternion.w = body.orientation.s;
  75518. }
  75519. };
  75520. OimoJSPlugin.prototype.getRadius = function (impostor) {
  75521. return impostor.physicsBody.shapes.radius;
  75522. };
  75523. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75524. var shape = impostor.physicsBody.shapes;
  75525. result.x = shape.halfWidth * 2;
  75526. result.y = shape.halfHeight * 2;
  75527. result.z = shape.halfDepth * 2;
  75528. };
  75529. OimoJSPlugin.prototype.dispose = function () {
  75530. this.world.clear();
  75531. };
  75532. return OimoJSPlugin;
  75533. }());
  75534. BABYLON.OimoJSPlugin = OimoJSPlugin;
  75535. })(BABYLON || (BABYLON = {}));
  75536. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  75537. var BABYLON;
  75538. (function (BABYLON) {
  75539. /*
  75540. * Based on jsTGALoader - Javascript loader for TGA file
  75541. * By Vincent Thibault
  75542. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  75543. */
  75544. var TGATools = /** @class */ (function () {
  75545. function TGATools() {
  75546. }
  75547. TGATools.GetTGAHeader = function (data) {
  75548. var offset = 0;
  75549. var header = {
  75550. id_length: data[offset++],
  75551. colormap_type: data[offset++],
  75552. image_type: data[offset++],
  75553. colormap_index: data[offset++] | data[offset++] << 8,
  75554. colormap_length: data[offset++] | data[offset++] << 8,
  75555. colormap_size: data[offset++],
  75556. origin: [
  75557. data[offset++] | data[offset++] << 8,
  75558. data[offset++] | data[offset++] << 8
  75559. ],
  75560. width: data[offset++] | data[offset++] << 8,
  75561. height: data[offset++] | data[offset++] << 8,
  75562. pixel_size: data[offset++],
  75563. flags: data[offset++]
  75564. };
  75565. return header;
  75566. };
  75567. TGATools.UploadContent = function (gl, data) {
  75568. // Not enough data to contain header ?
  75569. if (data.length < 19) {
  75570. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  75571. return;
  75572. }
  75573. // Read Header
  75574. var offset = 18;
  75575. var header = TGATools.GetTGAHeader(data);
  75576. // Assume it's a valid Targa file.
  75577. if (header.id_length + offset > data.length) {
  75578. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  75579. return;
  75580. }
  75581. // Skip not needed data
  75582. offset += header.id_length;
  75583. var use_rle = false;
  75584. var use_pal = false;
  75585. var use_grey = false;
  75586. // Get some informations.
  75587. switch (header.image_type) {
  75588. case TGATools._TYPE_RLE_INDEXED:
  75589. use_rle = true;
  75590. case TGATools._TYPE_INDEXED:
  75591. use_pal = true;
  75592. break;
  75593. case TGATools._TYPE_RLE_RGB:
  75594. use_rle = true;
  75595. case TGATools._TYPE_RGB:
  75596. // use_rgb = true;
  75597. break;
  75598. case TGATools._TYPE_RLE_GREY:
  75599. use_rle = true;
  75600. case TGATools._TYPE_GREY:
  75601. use_grey = true;
  75602. break;
  75603. }
  75604. var pixel_data;
  75605. // var numAlphaBits = header.flags & 0xf;
  75606. var pixel_size = header.pixel_size >> 3;
  75607. var pixel_total = header.width * header.height * pixel_size;
  75608. // Read palettes
  75609. var palettes;
  75610. if (use_pal) {
  75611. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  75612. }
  75613. // Read LRE
  75614. if (use_rle) {
  75615. pixel_data = new Uint8Array(pixel_total);
  75616. var c, count, i;
  75617. var localOffset = 0;
  75618. var pixels = new Uint8Array(pixel_size);
  75619. while (offset < pixel_total && localOffset < pixel_total) {
  75620. c = data[offset++];
  75621. count = (c & 0x7f) + 1;
  75622. // RLE pixels
  75623. if (c & 0x80) {
  75624. // Bind pixel tmp array
  75625. for (i = 0; i < pixel_size; ++i) {
  75626. pixels[i] = data[offset++];
  75627. }
  75628. // Copy pixel array
  75629. for (i = 0; i < count; ++i) {
  75630. pixel_data.set(pixels, localOffset + i * pixel_size);
  75631. }
  75632. localOffset += pixel_size * count;
  75633. }
  75634. else {
  75635. count *= pixel_size;
  75636. for (i = 0; i < count; ++i) {
  75637. pixel_data[localOffset + i] = data[offset++];
  75638. }
  75639. localOffset += count;
  75640. }
  75641. }
  75642. }
  75643. else {
  75644. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  75645. }
  75646. // Load to texture
  75647. var x_start, y_start, x_step, y_step, y_end, x_end;
  75648. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  75649. default:
  75650. case TGATools._ORIGIN_UL:
  75651. x_start = 0;
  75652. x_step = 1;
  75653. x_end = header.width;
  75654. y_start = 0;
  75655. y_step = 1;
  75656. y_end = header.height;
  75657. break;
  75658. case TGATools._ORIGIN_BL:
  75659. x_start = 0;
  75660. x_step = 1;
  75661. x_end = header.width;
  75662. y_start = header.height - 1;
  75663. y_step = -1;
  75664. y_end = -1;
  75665. break;
  75666. case TGATools._ORIGIN_UR:
  75667. x_start = header.width - 1;
  75668. x_step = -1;
  75669. x_end = -1;
  75670. y_start = 0;
  75671. y_step = 1;
  75672. y_end = header.height;
  75673. break;
  75674. case TGATools._ORIGIN_BR:
  75675. x_start = header.width - 1;
  75676. x_step = -1;
  75677. x_end = -1;
  75678. y_start = header.height - 1;
  75679. y_step = -1;
  75680. y_end = -1;
  75681. break;
  75682. }
  75683. // Load the specify method
  75684. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  75685. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  75686. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  75687. };
  75688. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75689. var image = pixel_data, colormap = palettes;
  75690. var width = header.width, height = header.height;
  75691. var color, i = 0, x, y;
  75692. var imageData = new Uint8Array(width * height * 4);
  75693. for (y = y_start; y !== y_end; y += y_step) {
  75694. for (x = x_start; x !== x_end; x += x_step, i++) {
  75695. color = image[i];
  75696. imageData[(x + width * y) * 4 + 3] = 255;
  75697. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  75698. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  75699. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  75700. }
  75701. }
  75702. return imageData;
  75703. };
  75704. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75705. var image = pixel_data;
  75706. var width = header.width, height = header.height;
  75707. var color, i = 0, x, y;
  75708. var imageData = new Uint8Array(width * height * 4);
  75709. for (y = y_start; y !== y_end; y += y_step) {
  75710. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75711. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  75712. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  75713. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  75714. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  75715. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  75716. }
  75717. }
  75718. return imageData;
  75719. };
  75720. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75721. var image = pixel_data;
  75722. var width = header.width, height = header.height;
  75723. var i = 0, x, y;
  75724. var imageData = new Uint8Array(width * height * 4);
  75725. for (y = y_start; y !== y_end; y += y_step) {
  75726. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  75727. imageData[(x + width * y) * 4 + 3] = 255;
  75728. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75729. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75730. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75731. }
  75732. }
  75733. return imageData;
  75734. };
  75735. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75736. var image = pixel_data;
  75737. var width = header.width, height = header.height;
  75738. var i = 0, x, y;
  75739. var imageData = new Uint8Array(width * height * 4);
  75740. for (y = y_start; y !== y_end; y += y_step) {
  75741. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  75742. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75743. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75744. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75745. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  75746. }
  75747. }
  75748. return imageData;
  75749. };
  75750. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75751. var image = pixel_data;
  75752. var width = header.width, height = header.height;
  75753. var color, i = 0, x, y;
  75754. var imageData = new Uint8Array(width * height * 4);
  75755. for (y = y_start; y !== y_end; y += y_step) {
  75756. for (x = x_start; x !== x_end; x += x_step, i++) {
  75757. color = image[i];
  75758. imageData[(x + width * y) * 4 + 0] = color;
  75759. imageData[(x + width * y) * 4 + 1] = color;
  75760. imageData[(x + width * y) * 4 + 2] = color;
  75761. imageData[(x + width * y) * 4 + 3] = 255;
  75762. }
  75763. }
  75764. return imageData;
  75765. };
  75766. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75767. var image = pixel_data;
  75768. var width = header.width, height = header.height;
  75769. var i = 0, x, y;
  75770. var imageData = new Uint8Array(width * height * 4);
  75771. for (y = y_start; y !== y_end; y += y_step) {
  75772. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75773. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  75774. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  75775. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75776. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  75777. }
  75778. }
  75779. return imageData;
  75780. };
  75781. //private static _TYPE_NO_DATA = 0;
  75782. TGATools._TYPE_INDEXED = 1;
  75783. TGATools._TYPE_RGB = 2;
  75784. TGATools._TYPE_GREY = 3;
  75785. TGATools._TYPE_RLE_INDEXED = 9;
  75786. TGATools._TYPE_RLE_RGB = 10;
  75787. TGATools._TYPE_RLE_GREY = 11;
  75788. TGATools._ORIGIN_MASK = 0x30;
  75789. TGATools._ORIGIN_SHIFT = 0x04;
  75790. TGATools._ORIGIN_BL = 0x00;
  75791. TGATools._ORIGIN_BR = 0x01;
  75792. TGATools._ORIGIN_UL = 0x02;
  75793. TGATools._ORIGIN_UR = 0x03;
  75794. return TGATools;
  75795. }());
  75796. BABYLON.TGATools = TGATools;
  75797. })(BABYLON || (BABYLON = {}));
  75798. //# sourceMappingURL=babylon.tga.js.map
  75799. var BABYLON;
  75800. (function (BABYLON) {
  75801. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  75802. // All values and structures referenced from:
  75803. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  75804. var DDS_MAGIC = 0x20534444;
  75805. var
  75806. //DDSD_CAPS = 0x1,
  75807. //DDSD_HEIGHT = 0x2,
  75808. //DDSD_WIDTH = 0x4,
  75809. //DDSD_PITCH = 0x8,
  75810. //DDSD_PIXELFORMAT = 0x1000,
  75811. DDSD_MIPMAPCOUNT = 0x20000;
  75812. //DDSD_LINEARSIZE = 0x80000,
  75813. //DDSD_DEPTH = 0x800000;
  75814. // var DDSCAPS_COMPLEX = 0x8,
  75815. // DDSCAPS_MIPMAP = 0x400000,
  75816. // DDSCAPS_TEXTURE = 0x1000;
  75817. var DDSCAPS2_CUBEMAP = 0x200;
  75818. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  75819. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  75820. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  75821. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  75822. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  75823. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  75824. // DDSCAPS2_VOLUME = 0x200000;
  75825. var
  75826. //DDPF_ALPHAPIXELS = 0x1,
  75827. //DDPF_ALPHA = 0x2,
  75828. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  75829. //DDPF_YUV = 0x200,
  75830. DDPF_LUMINANCE = 0x20000;
  75831. function FourCCToInt32(value) {
  75832. return value.charCodeAt(0) +
  75833. (value.charCodeAt(1) << 8) +
  75834. (value.charCodeAt(2) << 16) +
  75835. (value.charCodeAt(3) << 24);
  75836. }
  75837. function Int32ToFourCC(value) {
  75838. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  75839. }
  75840. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  75841. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  75842. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  75843. var FOURCC_DX10 = FourCCToInt32("DX10");
  75844. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  75845. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  75846. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  75847. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  75848. var headerLengthInt = 31; // The header length in 32 bit ints
  75849. // Offsets into the header array
  75850. var off_magic = 0;
  75851. var off_size = 1;
  75852. var off_flags = 2;
  75853. var off_height = 3;
  75854. var off_width = 4;
  75855. var off_mipmapCount = 7;
  75856. var off_pfFlags = 20;
  75857. var off_pfFourCC = 21;
  75858. var off_RGBbpp = 22;
  75859. var off_RMask = 23;
  75860. var off_GMask = 24;
  75861. var off_BMask = 25;
  75862. var off_AMask = 26;
  75863. // var off_caps1 = 27;
  75864. var off_caps2 = 28;
  75865. // var off_caps3 = 29;
  75866. // var off_caps4 = 30;
  75867. var off_dxgiFormat = 32;
  75868. ;
  75869. var DDSTools = /** @class */ (function () {
  75870. function DDSTools() {
  75871. }
  75872. DDSTools.GetDDSInfo = function (arrayBuffer) {
  75873. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75874. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  75875. var mipmapCount = 1;
  75876. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  75877. mipmapCount = Math.max(1, header[off_mipmapCount]);
  75878. }
  75879. var fourCC = header[off_pfFourCC];
  75880. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  75881. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75882. switch (fourCC) {
  75883. case FOURCC_D3DFMT_R16G16B16A16F:
  75884. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75885. break;
  75886. case FOURCC_D3DFMT_R32G32B32A32F:
  75887. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75888. break;
  75889. case FOURCC_DX10:
  75890. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  75891. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75892. break;
  75893. }
  75894. }
  75895. return {
  75896. width: header[off_width],
  75897. height: header[off_height],
  75898. mipmapCount: mipmapCount,
  75899. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  75900. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  75901. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  75902. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  75903. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  75904. dxgiFormat: dxgiFormat,
  75905. textureType: textureType
  75906. };
  75907. };
  75908. DDSTools._ToHalfFloat = function (value) {
  75909. if (!DDSTools._FloatView) {
  75910. DDSTools._FloatView = new Float32Array(1);
  75911. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  75912. }
  75913. DDSTools._FloatView[0] = value;
  75914. var x = DDSTools._Int32View[0];
  75915. var bits = (x >> 16) & 0x8000; /* Get the sign */
  75916. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  75917. var e = (x >> 23) & 0xff; /* Using int is faster here */
  75918. /* If zero, or denormal, or exponent underflows too much for a denormal
  75919. * half, return signed zero. */
  75920. if (e < 103) {
  75921. return bits;
  75922. }
  75923. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  75924. if (e > 142) {
  75925. bits |= 0x7c00;
  75926. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  75927. * not Inf, so make sure we set one mantissa bit too. */
  75928. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  75929. return bits;
  75930. }
  75931. /* If exponent underflows but not too much, return a denormal */
  75932. if (e < 113) {
  75933. m |= 0x0800;
  75934. /* Extra rounding may overflow and set mantissa to 0 and exponent
  75935. * to 1, which is OK. */
  75936. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  75937. return bits;
  75938. }
  75939. bits |= ((e - 112) << 10) | (m >> 1);
  75940. bits += m & 1;
  75941. return bits;
  75942. };
  75943. DDSTools._FromHalfFloat = function (value) {
  75944. var s = (value & 0x8000) >> 15;
  75945. var e = (value & 0x7C00) >> 10;
  75946. var f = value & 0x03FF;
  75947. if (e === 0) {
  75948. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  75949. }
  75950. else if (e == 0x1F) {
  75951. return f ? NaN : ((s ? -1 : 1) * Infinity);
  75952. }
  75953. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  75954. };
  75955. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75956. var destArray = new Float32Array(dataLength);
  75957. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75958. var index = 0;
  75959. for (var y = 0; y < height; y++) {
  75960. for (var x = 0; x < width; x++) {
  75961. var srcPos = (x + y * width) * 4;
  75962. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  75963. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  75964. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  75965. if (DDSTools.StoreLODInAlphaChannel) {
  75966. destArray[index + 3] = lod;
  75967. }
  75968. else {
  75969. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  75970. }
  75971. index += 4;
  75972. }
  75973. }
  75974. return destArray;
  75975. };
  75976. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75977. if (DDSTools.StoreLODInAlphaChannel) {
  75978. var destArray = new Uint16Array(dataLength);
  75979. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75980. var index = 0;
  75981. for (var y = 0; y < height; y++) {
  75982. for (var x = 0; x < width; x++) {
  75983. var srcPos = (x + y * width) * 4;
  75984. destArray[index] = srcData[srcPos];
  75985. destArray[index + 1] = srcData[srcPos + 1];
  75986. destArray[index + 2] = srcData[srcPos + 2];
  75987. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  75988. index += 4;
  75989. }
  75990. }
  75991. return destArray;
  75992. }
  75993. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  75994. };
  75995. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75996. if (DDSTools.StoreLODInAlphaChannel) {
  75997. var destArray = new Float32Array(dataLength);
  75998. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75999. var index = 0;
  76000. for (var y = 0; y < height; y++) {
  76001. for (var x = 0; x < width; x++) {
  76002. var srcPos = (x + y * width) * 4;
  76003. destArray[index] = srcData[srcPos];
  76004. destArray[index + 1] = srcData[srcPos + 1];
  76005. destArray[index + 2] = srcData[srcPos + 2];
  76006. destArray[index + 3] = lod;
  76007. index += 4;
  76008. }
  76009. }
  76010. return destArray;
  76011. }
  76012. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  76013. };
  76014. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76015. var destArray = new Uint8Array(dataLength);
  76016. var srcData = new Float32Array(arrayBuffer, dataOffset);
  76017. var index = 0;
  76018. for (var y = 0; y < height; y++) {
  76019. for (var x = 0; x < width; x++) {
  76020. var srcPos = (x + y * width) * 4;
  76021. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  76022. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  76023. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  76024. if (DDSTools.StoreLODInAlphaChannel) {
  76025. destArray[index + 3] = lod;
  76026. }
  76027. else {
  76028. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  76029. }
  76030. index += 4;
  76031. }
  76032. }
  76033. return destArray;
  76034. };
  76035. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76036. var destArray = new Uint8Array(dataLength);
  76037. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76038. var index = 0;
  76039. for (var y = 0; y < height; y++) {
  76040. for (var x = 0; x < width; x++) {
  76041. var srcPos = (x + y * width) * 4;
  76042. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  76043. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  76044. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  76045. if (DDSTools.StoreLODInAlphaChannel) {
  76046. destArray[index + 3] = lod;
  76047. }
  76048. else {
  76049. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  76050. }
  76051. index += 4;
  76052. }
  76053. }
  76054. return destArray;
  76055. };
  76056. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  76057. var byteArray = new Uint8Array(dataLength);
  76058. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76059. var index = 0;
  76060. for (var y = 0; y < height; y++) {
  76061. for (var x = 0; x < width; x++) {
  76062. var srcPos = (x + y * width) * 4;
  76063. byteArray[index] = srcData[srcPos + rOffset];
  76064. byteArray[index + 1] = srcData[srcPos + gOffset];
  76065. byteArray[index + 2] = srcData[srcPos + bOffset];
  76066. byteArray[index + 3] = srcData[srcPos + aOffset];
  76067. index += 4;
  76068. }
  76069. }
  76070. return byteArray;
  76071. };
  76072. DDSTools._ExtractLongWordOrder = function (value) {
  76073. if (value === 0 || value === 255 || value === -16777216) {
  76074. return 0;
  76075. }
  76076. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  76077. };
  76078. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  76079. var byteArray = new Uint8Array(dataLength);
  76080. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76081. var index = 0;
  76082. for (var y = 0; y < height; y++) {
  76083. for (var x = 0; x < width; x++) {
  76084. var srcPos = (x + y * width) * 3;
  76085. byteArray[index] = srcData[srcPos + rOffset];
  76086. byteArray[index + 1] = srcData[srcPos + gOffset];
  76087. byteArray[index + 2] = srcData[srcPos + bOffset];
  76088. index += 3;
  76089. }
  76090. }
  76091. return byteArray;
  76092. };
  76093. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  76094. var byteArray = new Uint8Array(dataLength);
  76095. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76096. var index = 0;
  76097. for (var y = 0; y < height; y++) {
  76098. for (var x = 0; x < width; x++) {
  76099. var srcPos = (x + y * width);
  76100. byteArray[index] = srcData[srcPos];
  76101. index++;
  76102. }
  76103. }
  76104. return byteArray;
  76105. };
  76106. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  76107. if (lodIndex === void 0) { lodIndex = -1; }
  76108. var ext = engine.getCaps().s3tc;
  76109. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  76110. var fourCC, width, height, dataLength = 0, dataOffset;
  76111. var byteArray, mipmapCount, mip;
  76112. var internalFormat = 0;
  76113. var format = 0;
  76114. var blockBytes = 1;
  76115. if (header[off_magic] !== DDS_MAGIC) {
  76116. BABYLON.Tools.Error("Invalid magic number in DDS header");
  76117. return;
  76118. }
  76119. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  76120. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  76121. return;
  76122. }
  76123. if (info.isCompressed && !ext) {
  76124. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  76125. return;
  76126. }
  76127. var bpp = header[off_RGBbpp];
  76128. dataOffset = header[off_size] + 4;
  76129. var computeFormats = false;
  76130. if (info.isFourCC) {
  76131. fourCC = header[off_pfFourCC];
  76132. switch (fourCC) {
  76133. case FOURCC_DXT1:
  76134. blockBytes = 8;
  76135. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  76136. break;
  76137. case FOURCC_DXT3:
  76138. blockBytes = 16;
  76139. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  76140. break;
  76141. case FOURCC_DXT5:
  76142. blockBytes = 16;
  76143. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  76144. break;
  76145. case FOURCC_D3DFMT_R16G16B16A16F:
  76146. computeFormats = true;
  76147. break;
  76148. case FOURCC_D3DFMT_R32G32B32A32F:
  76149. computeFormats = true;
  76150. break;
  76151. case FOURCC_DX10:
  76152. // There is an additionnal header so dataOffset need to be changed
  76153. dataOffset += 5 * 4; // 5 uints
  76154. var supported = false;
  76155. switch (info.dxgiFormat) {
  76156. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  76157. computeFormats = true;
  76158. supported = true;
  76159. break;
  76160. case DXGI_FORMAT_B8G8R8X8_UNORM:
  76161. info.isRGB = true;
  76162. info.isFourCC = false;
  76163. bpp = 32;
  76164. supported = true;
  76165. break;
  76166. }
  76167. if (supported) {
  76168. break;
  76169. }
  76170. default:
  76171. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  76172. return;
  76173. }
  76174. }
  76175. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  76176. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  76177. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  76178. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  76179. if (computeFormats) {
  76180. format = engine._getWebGLTextureType(info.textureType);
  76181. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76182. }
  76183. mipmapCount = 1;
  76184. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  76185. mipmapCount = Math.max(1, header[off_mipmapCount]);
  76186. }
  76187. for (var face = 0; face < faces; face++) {
  76188. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  76189. width = header[off_width];
  76190. height = header[off_height];
  76191. for (mip = 0; mip < mipmapCount; ++mip) {
  76192. if (lodIndex === -1 || lodIndex === mip) {
  76193. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  76194. var i = (lodIndex === -1) ? mip : 0;
  76195. if (!info.isCompressed && info.isFourCC) {
  76196. dataLength = width * height * 4;
  76197. var floatArray = null;
  76198. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  76199. if (bpp === 128) {
  76200. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76201. }
  76202. else if (bpp === 64) {
  76203. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76204. }
  76205. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76206. format = engine._getWebGLTextureType(info.textureType);
  76207. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76208. }
  76209. else {
  76210. if (bpp === 128) {
  76211. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76212. }
  76213. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  76214. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76215. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76216. format = engine._getWebGLTextureType(info.textureType);
  76217. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76218. }
  76219. else {
  76220. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76221. }
  76222. }
  76223. if (floatArray) {
  76224. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  76225. }
  76226. }
  76227. else if (info.isRGB) {
  76228. if (bpp === 24) {
  76229. dataLength = width * height * 3;
  76230. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  76231. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  76232. }
  76233. else {
  76234. dataLength = width * height * 4;
  76235. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  76236. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  76237. }
  76238. }
  76239. else if (info.isLuminance) {
  76240. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  76241. var unpaddedRowSize = width;
  76242. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  76243. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  76244. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  76245. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  76246. }
  76247. else {
  76248. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  76249. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  76250. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  76251. }
  76252. }
  76253. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  76254. width *= 0.5;
  76255. height *= 0.5;
  76256. width = Math.max(1.0, width);
  76257. height = Math.max(1.0, height);
  76258. }
  76259. if (currentFace !== undefined) {
  76260. // Loading a single face
  76261. break;
  76262. }
  76263. }
  76264. };
  76265. DDSTools.StoreLODInAlphaChannel = false;
  76266. return DDSTools;
  76267. }());
  76268. BABYLON.DDSTools = DDSTools;
  76269. })(BABYLON || (BABYLON = {}));
  76270. //# sourceMappingURL=babylon.dds.js.map
  76271. var BABYLON;
  76272. (function (BABYLON) {
  76273. /**
  76274. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  76275. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  76276. */
  76277. var KhronosTextureContainer = /** @class */ (function () {
  76278. /**
  76279. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  76280. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  76281. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  76282. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  76283. */
  76284. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  76285. this.arrayBuffer = arrayBuffer;
  76286. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  76287. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  76288. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  76289. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  76290. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  76291. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  76292. BABYLON.Tools.Error("texture missing KTX identifier");
  76293. return;
  76294. }
  76295. // load the reset of the header in native 32 bit int
  76296. var header = new Int32Array(this.arrayBuffer, 12, 13);
  76297. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  76298. var oppositeEndianess = header[0] === 0x01020304;
  76299. // read all the header elements in order they exist in the file, without modification (sans endainness)
  76300. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  76301. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  76302. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  76303. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  76304. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  76305. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  76306. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  76307. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  76308. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  76309. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  76310. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  76311. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  76312. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  76313. if (this.glType !== 0) {
  76314. BABYLON.Tools.Error("only compressed formats currently supported");
  76315. return;
  76316. }
  76317. else {
  76318. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  76319. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  76320. }
  76321. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  76322. BABYLON.Tools.Error("only 2D textures currently supported");
  76323. return;
  76324. }
  76325. if (this.numberOfArrayElements !== 0) {
  76326. BABYLON.Tools.Error("texture arrays not currently supported");
  76327. return;
  76328. }
  76329. if (this.numberOfFaces !== facesExpected) {
  76330. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  76331. return;
  76332. }
  76333. // we now have a completely validated file, so could use existence of loadType as success
  76334. // would need to make this more elaborate & adjust checks above to support more than one load type
  76335. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  76336. }
  76337. // not as fast hardware based, but will probably never need to use
  76338. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  76339. return ((val & 0xFF) << 24)
  76340. | ((val & 0xFF00) << 8)
  76341. | ((val >> 8) & 0xFF00)
  76342. | ((val >> 24) & 0xFF);
  76343. };
  76344. /**
  76345. * It is assumed that the texture has already been created & is currently bound
  76346. */
  76347. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  76348. switch (this.loadType) {
  76349. case KhronosTextureContainer.COMPRESSED_2D:
  76350. this._upload2DCompressedLevels(gl, loadMipmaps);
  76351. break;
  76352. case KhronosTextureContainer.TEX_2D:
  76353. case KhronosTextureContainer.COMPRESSED_3D:
  76354. case KhronosTextureContainer.TEX_3D:
  76355. }
  76356. };
  76357. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  76358. // initialize width & height for level 1
  76359. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  76360. var width = this.pixelWidth;
  76361. var height = this.pixelHeight;
  76362. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  76363. for (var level = 0; level < mipmapCount; level++) {
  76364. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  76365. for (var face = 0; face < this.numberOfFaces; face++) {
  76366. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  76367. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  76368. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  76369. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  76370. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  76371. }
  76372. width = Math.max(1.0, width * 0.5);
  76373. height = Math.max(1.0, height * 0.5);
  76374. }
  76375. };
  76376. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  76377. // load types
  76378. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  76379. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  76380. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  76381. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  76382. return KhronosTextureContainer;
  76383. }());
  76384. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  76385. })(BABYLON || (BABYLON = {}));
  76386. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  76387. var BABYLON;
  76388. (function (BABYLON) {
  76389. var Debug = /** @class */ (function () {
  76390. function Debug() {
  76391. }
  76392. Debug.AxesViewer = /** @class */ (function () {
  76393. function AxesViewer(scene, scaleLines) {
  76394. if (scaleLines === void 0) { scaleLines = 1; }
  76395. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76396. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76397. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76398. this.scaleLines = 1;
  76399. this.scaleLines = scaleLines;
  76400. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  76401. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  76402. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  76403. this._xmesh.renderingGroupId = 2;
  76404. this._ymesh.renderingGroupId = 2;
  76405. this._zmesh.renderingGroupId = 2;
  76406. this._xmesh.material.checkReadyOnlyOnce = true;
  76407. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  76408. this._ymesh.material.checkReadyOnlyOnce = true;
  76409. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  76410. this._zmesh.material.checkReadyOnlyOnce = true;
  76411. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  76412. this.scene = scene;
  76413. }
  76414. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  76415. var scaleLines = this.scaleLines;
  76416. if (this._xmesh) {
  76417. this._xmesh.position.copyFrom(position);
  76418. }
  76419. if (this._ymesh) {
  76420. this._ymesh.position.copyFrom(position);
  76421. }
  76422. if (this._zmesh) {
  76423. this._zmesh.position.copyFrom(position);
  76424. }
  76425. var point2 = this._xline[1];
  76426. point2.x = xaxis.x * scaleLines;
  76427. point2.y = xaxis.y * scaleLines;
  76428. point2.z = xaxis.z * scaleLines;
  76429. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  76430. point2 = this._yline[1];
  76431. point2.x = yaxis.x * scaleLines;
  76432. point2.y = yaxis.y * scaleLines;
  76433. point2.z = yaxis.z * scaleLines;
  76434. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  76435. point2 = this._zline[1];
  76436. point2.x = zaxis.x * scaleLines;
  76437. point2.y = zaxis.y * scaleLines;
  76438. point2.z = zaxis.z * scaleLines;
  76439. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  76440. };
  76441. AxesViewer.prototype.dispose = function () {
  76442. if (this._xmesh) {
  76443. this._xmesh.dispose();
  76444. }
  76445. if (this._ymesh) {
  76446. this._ymesh.dispose();
  76447. }
  76448. if (this._zmesh) {
  76449. this._zmesh.dispose();
  76450. }
  76451. this._xmesh = null;
  76452. this._ymesh = null;
  76453. this._zmesh = null;
  76454. this.scene = null;
  76455. };
  76456. return AxesViewer;
  76457. }());
  76458. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  76459. __extends(BoneAxesViewer, _super);
  76460. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  76461. if (scaleLines === void 0) { scaleLines = 1; }
  76462. var _this = _super.call(this, scene, scaleLines) || this;
  76463. _this.pos = BABYLON.Vector3.Zero();
  76464. _this.xaxis = BABYLON.Vector3.Zero();
  76465. _this.yaxis = BABYLON.Vector3.Zero();
  76466. _this.zaxis = BABYLON.Vector3.Zero();
  76467. _this.mesh = mesh;
  76468. _this.bone = bone;
  76469. return _this;
  76470. }
  76471. BoneAxesViewer.prototype.update = function () {
  76472. if (!this.mesh || !this.bone) {
  76473. return;
  76474. }
  76475. var bone = this.bone;
  76476. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  76477. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  76478. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  76479. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  76480. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  76481. };
  76482. BoneAxesViewer.prototype.dispose = function () {
  76483. if (this.mesh) {
  76484. this.mesh = null;
  76485. this.bone = null;
  76486. _super.prototype.dispose.call(this);
  76487. }
  76488. };
  76489. return BoneAxesViewer;
  76490. }(Debug.AxesViewer));
  76491. Debug.PhysicsViewer = /** @class */ (function () {
  76492. function PhysicsViewer(scene) {
  76493. this._impostors = [];
  76494. this._meshes = [];
  76495. this._numMeshes = 0;
  76496. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76497. var physicEngine = this._scene.getPhysicsEngine();
  76498. if (physicEngine) {
  76499. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  76500. }
  76501. }
  76502. PhysicsViewer.prototype._updateDebugMeshes = function () {
  76503. var plugin = this._physicsEnginePlugin;
  76504. for (var i = 0; i < this._numMeshes; i++) {
  76505. var impostor = this._impostors[i];
  76506. if (!impostor) {
  76507. continue;
  76508. }
  76509. if (impostor.isDisposed) {
  76510. this.hideImpostor(this._impostors[i--]);
  76511. }
  76512. else {
  76513. var mesh = this._meshes[i];
  76514. if (mesh && plugin) {
  76515. plugin.syncMeshWithImpostor(mesh, impostor);
  76516. }
  76517. }
  76518. }
  76519. };
  76520. PhysicsViewer.prototype.showImpostor = function (impostor) {
  76521. if (!this._scene) {
  76522. return;
  76523. }
  76524. for (var i = 0; i < this._numMeshes; i++) {
  76525. if (this._impostors[i] == impostor) {
  76526. return;
  76527. }
  76528. }
  76529. var debugMesh = this._getDebugMesh(impostor, this._scene);
  76530. if (debugMesh) {
  76531. this._impostors[this._numMeshes] = impostor;
  76532. this._meshes[this._numMeshes] = debugMesh;
  76533. if (this._numMeshes === 0) {
  76534. this._renderFunction = this._updateDebugMeshes.bind(this);
  76535. this._scene.registerBeforeRender(this._renderFunction);
  76536. }
  76537. this._numMeshes++;
  76538. }
  76539. };
  76540. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  76541. if (!impostor || !this._scene) {
  76542. return;
  76543. }
  76544. var removed = false;
  76545. for (var i = 0; i < this._numMeshes; i++) {
  76546. if (this._impostors[i] == impostor) {
  76547. var mesh = this._meshes[i];
  76548. if (!mesh) {
  76549. continue;
  76550. }
  76551. this._scene.removeMesh(mesh);
  76552. mesh.dispose();
  76553. this._numMeshes--;
  76554. if (this._numMeshes > 0) {
  76555. this._meshes[i] = this._meshes[this._numMeshes];
  76556. this._impostors[i] = this._impostors[this._numMeshes];
  76557. this._meshes[this._numMeshes] = null;
  76558. this._impostors[this._numMeshes] = null;
  76559. }
  76560. else {
  76561. this._meshes[0] = null;
  76562. this._impostors[0] = null;
  76563. }
  76564. removed = true;
  76565. break;
  76566. }
  76567. }
  76568. if (removed && this._numMeshes === 0) {
  76569. this._scene.unregisterBeforeRender(this._renderFunction);
  76570. }
  76571. };
  76572. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  76573. if (!this._debugMaterial) {
  76574. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  76575. this._debugMaterial.wireframe = true;
  76576. }
  76577. return this._debugMaterial;
  76578. };
  76579. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  76580. if (!this._debugBoxMesh) {
  76581. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  76582. this._debugBoxMesh.renderingGroupId = 1;
  76583. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76584. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  76585. scene.removeMesh(this._debugBoxMesh);
  76586. }
  76587. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  76588. };
  76589. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  76590. if (!this._debugSphereMesh) {
  76591. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  76592. this._debugSphereMesh.renderingGroupId = 1;
  76593. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76594. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  76595. scene.removeMesh(this._debugSphereMesh);
  76596. }
  76597. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  76598. };
  76599. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  76600. var mesh = null;
  76601. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  76602. mesh = this._getDebugBoxMesh(scene);
  76603. impostor.getBoxSizeToRef(mesh.scaling);
  76604. }
  76605. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  76606. mesh = this._getDebugSphereMesh(scene);
  76607. var radius = impostor.getRadius();
  76608. mesh.scaling.x = radius * 2;
  76609. mesh.scaling.y = radius * 2;
  76610. mesh.scaling.z = radius * 2;
  76611. }
  76612. return mesh;
  76613. };
  76614. PhysicsViewer.prototype.dispose = function () {
  76615. for (var i = 0; i < this._numMeshes; i++) {
  76616. this.hideImpostor(this._impostors[i]);
  76617. }
  76618. if (this._debugBoxMesh) {
  76619. this._debugBoxMesh.dispose();
  76620. }
  76621. if (this._debugSphereMesh) {
  76622. this._debugSphereMesh.dispose();
  76623. }
  76624. if (this._debugMaterial) {
  76625. this._debugMaterial.dispose();
  76626. }
  76627. this._impostors.length = 0;
  76628. this._scene = null;
  76629. this._physicsEnginePlugin = null;
  76630. };
  76631. return PhysicsViewer;
  76632. }());
  76633. Debug.SkeletonViewer = /** @class */ (function () {
  76634. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  76635. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  76636. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  76637. this.skeleton = skeleton;
  76638. this.mesh = mesh;
  76639. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  76640. this.renderingGroupId = renderingGroupId;
  76641. this.color = BABYLON.Color3.White();
  76642. this._debugLines = new Array();
  76643. this._isEnabled = false;
  76644. this._scene = scene;
  76645. this.update();
  76646. this._renderFunction = this.update.bind(this);
  76647. }
  76648. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  76649. get: function () {
  76650. return this._isEnabled;
  76651. },
  76652. set: function (value) {
  76653. if (this._isEnabled === value) {
  76654. return;
  76655. }
  76656. this._isEnabled = value;
  76657. if (value) {
  76658. this._scene.registerBeforeRender(this._renderFunction);
  76659. }
  76660. else {
  76661. this._scene.unregisterBeforeRender(this._renderFunction);
  76662. }
  76663. },
  76664. enumerable: true,
  76665. configurable: true
  76666. });
  76667. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  76668. if (x === void 0) { x = 0; }
  76669. if (y === void 0) { y = 0; }
  76670. if (z === void 0) { z = 0; }
  76671. var tmat = BABYLON.Tmp.Matrix[0];
  76672. var parentBone = bone.getParent();
  76673. tmat.copyFrom(bone.getLocalMatrix());
  76674. if (x !== 0 || y !== 0 || z !== 0) {
  76675. var tmat2 = BABYLON.Tmp.Matrix[1];
  76676. BABYLON.Matrix.IdentityToRef(tmat2);
  76677. tmat2.m[12] = x;
  76678. tmat2.m[13] = y;
  76679. tmat2.m[14] = z;
  76680. tmat2.multiplyToRef(tmat, tmat);
  76681. }
  76682. if (parentBone) {
  76683. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  76684. }
  76685. tmat.multiplyToRef(meshMat, tmat);
  76686. position.x = tmat.m[12];
  76687. position.y = tmat.m[13];
  76688. position.z = tmat.m[14];
  76689. };
  76690. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  76691. var len = bones.length;
  76692. var meshPos = this.mesh.position;
  76693. for (var i = 0; i < len; i++) {
  76694. var bone = bones[i];
  76695. var points = this._debugLines[i];
  76696. if (!points) {
  76697. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76698. this._debugLines[i] = points;
  76699. }
  76700. this._getBonePosition(points[0], bone, meshMat);
  76701. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  76702. points[0].subtractInPlace(meshPos);
  76703. points[1].subtractInPlace(meshPos);
  76704. }
  76705. };
  76706. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  76707. var len = bones.length;
  76708. var boneNum = 0;
  76709. var meshPos = this.mesh.position;
  76710. for (var i = len - 1; i >= 0; i--) {
  76711. var childBone = bones[i];
  76712. var parentBone = childBone.getParent();
  76713. if (!parentBone) {
  76714. continue;
  76715. }
  76716. var points = this._debugLines[boneNum];
  76717. if (!points) {
  76718. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76719. this._debugLines[boneNum] = points;
  76720. }
  76721. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  76722. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  76723. points[0].subtractInPlace(meshPos);
  76724. points[1].subtractInPlace(meshPos);
  76725. boneNum++;
  76726. }
  76727. };
  76728. SkeletonViewer.prototype.update = function () {
  76729. if (this.autoUpdateBonesMatrices) {
  76730. this.skeleton.computeAbsoluteTransforms();
  76731. }
  76732. if (this.skeleton.bones[0].length === undefined) {
  76733. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76734. }
  76735. else {
  76736. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76737. }
  76738. if (!this._debugMesh) {
  76739. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  76740. this._debugMesh.renderingGroupId = this.renderingGroupId;
  76741. }
  76742. else {
  76743. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  76744. }
  76745. this._debugMesh.position.copyFrom(this.mesh.position);
  76746. this._debugMesh.color = this.color;
  76747. };
  76748. SkeletonViewer.prototype.dispose = function () {
  76749. if (this._debugMesh) {
  76750. this.isEnabled = false;
  76751. this._debugMesh.dispose();
  76752. this._debugMesh = null;
  76753. }
  76754. };
  76755. return SkeletonViewer;
  76756. }());
  76757. return Debug;
  76758. }());
  76759. BABYLON.Debug = Debug;
  76760. })(BABYLON || (BABYLON = {}));
  76761. //# sourceMappingURL=babylon.debugModules.js.map
  76762. var BABYLON;
  76763. (function (BABYLON) {
  76764. var RayHelper = /** @class */ (function () {
  76765. function RayHelper(ray) {
  76766. this.ray = ray;
  76767. }
  76768. RayHelper.CreateAndShow = function (ray, scene, color) {
  76769. var helper = new RayHelper(ray);
  76770. helper.show(scene, color);
  76771. return helper;
  76772. };
  76773. RayHelper.prototype.show = function (scene, color) {
  76774. if (!this._renderFunction && this.ray) {
  76775. var ray = this.ray;
  76776. this._renderFunction = this._render.bind(this);
  76777. this._scene = scene;
  76778. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  76779. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  76780. if (this._renderFunction) {
  76781. this._scene.registerBeforeRender(this._renderFunction);
  76782. }
  76783. }
  76784. if (color && this._renderLine) {
  76785. this._renderLine.color.copyFrom(color);
  76786. }
  76787. };
  76788. RayHelper.prototype.hide = function () {
  76789. if (this._renderFunction && this._scene) {
  76790. this._scene.unregisterBeforeRender(this._renderFunction);
  76791. this._scene = null;
  76792. this._renderFunction = null;
  76793. if (this._renderLine) {
  76794. this._renderLine.dispose();
  76795. this._renderLine = null;
  76796. }
  76797. this._renderPoints = [];
  76798. }
  76799. };
  76800. RayHelper.prototype._render = function () {
  76801. var ray = this.ray;
  76802. if (!ray) {
  76803. return;
  76804. }
  76805. var point = this._renderPoints[1];
  76806. var len = Math.min(ray.length, 1000000);
  76807. point.copyFrom(ray.direction);
  76808. point.scaleInPlace(len);
  76809. point.addInPlace(ray.origin);
  76810. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  76811. };
  76812. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  76813. this._attachedToMesh = mesh;
  76814. var ray = this.ray;
  76815. if (!ray) {
  76816. return;
  76817. }
  76818. if (!ray.direction) {
  76819. ray.direction = BABYLON.Vector3.Zero();
  76820. }
  76821. if (!ray.origin) {
  76822. ray.origin = BABYLON.Vector3.Zero();
  76823. }
  76824. if (length) {
  76825. ray.length = length;
  76826. }
  76827. if (!meshSpaceOrigin) {
  76828. meshSpaceOrigin = BABYLON.Vector3.Zero();
  76829. }
  76830. if (!meshSpaceDirection) {
  76831. // -1 so that this will work with Mesh.lookAt
  76832. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  76833. }
  76834. if (!this._meshSpaceDirection) {
  76835. this._meshSpaceDirection = meshSpaceDirection.clone();
  76836. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  76837. }
  76838. else {
  76839. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  76840. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  76841. }
  76842. if (!this._updateToMeshFunction) {
  76843. this._updateToMeshFunction = this._updateToMesh.bind(this);
  76844. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  76845. }
  76846. this._updateToMesh();
  76847. };
  76848. RayHelper.prototype.detachFromMesh = function () {
  76849. if (this._attachedToMesh) {
  76850. if (this._updateToMeshFunction) {
  76851. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  76852. }
  76853. this._attachedToMesh = null;
  76854. this._updateToMeshFunction = null;
  76855. }
  76856. };
  76857. RayHelper.prototype._updateToMesh = function () {
  76858. var ray = this.ray;
  76859. if (!this._attachedToMesh || !ray) {
  76860. return;
  76861. }
  76862. if (this._attachedToMesh._isDisposed) {
  76863. this.detachFromMesh();
  76864. return;
  76865. }
  76866. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  76867. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  76868. };
  76869. RayHelper.prototype.dispose = function () {
  76870. this.hide();
  76871. this.detachFromMesh();
  76872. this.ray = null;
  76873. };
  76874. return RayHelper;
  76875. }());
  76876. BABYLON.RayHelper = RayHelper;
  76877. })(BABYLON || (BABYLON = {}));
  76878. //# sourceMappingURL=babylon.rayHelper.js.map
  76879. var BABYLON;
  76880. (function (BABYLON) {
  76881. // load the inspector using require, if not present in the global namespace.
  76882. var DebugLayer = /** @class */ (function () {
  76883. function DebugLayer(scene) {
  76884. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76885. this._scene = scene;
  76886. // load inspector using require, if it doesn't exist on the global namespace.
  76887. }
  76888. /** Creates the inspector window. */
  76889. DebugLayer.prototype._createInspector = function (config) {
  76890. if (config === void 0) { config = {}; }
  76891. var popup = config.popup || false;
  76892. var initialTab = config.initialTab || 0;
  76893. var parentElement = config.parentElement || null;
  76894. if (!this._inspector) {
  76895. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76896. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  76897. } // else nothing to do,; instance is already existing
  76898. };
  76899. DebugLayer.prototype.isVisible = function () {
  76900. if (!this._inspector) {
  76901. return false;
  76902. }
  76903. return true;
  76904. };
  76905. DebugLayer.prototype.hide = function () {
  76906. if (this._inspector) {
  76907. try {
  76908. this._inspector.dispose();
  76909. }
  76910. catch (e) {
  76911. // If the inspector has been removed directly from the inspector tool
  76912. }
  76913. this._inspector = null;
  76914. }
  76915. };
  76916. DebugLayer.prototype.show = function (config) {
  76917. if (config === void 0) { config = {}; }
  76918. if (typeof this.BJSINSPECTOR == 'undefined') {
  76919. // Load inspector and add it to the DOM
  76920. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  76921. }
  76922. else {
  76923. // Otherwise creates the inspector
  76924. this._createInspector(config);
  76925. }
  76926. };
  76927. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  76928. return DebugLayer;
  76929. }());
  76930. BABYLON.DebugLayer = DebugLayer;
  76931. })(BABYLON || (BABYLON = {}));
  76932. //# sourceMappingURL=babylon.debugLayer.js.map
  76933. var BABYLON;
  76934. (function (BABYLON) {
  76935. var BoundingBoxRenderer = /** @class */ (function () {
  76936. function BoundingBoxRenderer(scene) {
  76937. this.frontColor = new BABYLON.Color3(1, 1, 1);
  76938. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  76939. this.showBackLines = true;
  76940. this.renderList = new BABYLON.SmartArray(32);
  76941. this._vertexBuffers = {};
  76942. this._scene = scene;
  76943. }
  76944. BoundingBoxRenderer.prototype._prepareRessources = function () {
  76945. if (this._colorShader) {
  76946. return;
  76947. }
  76948. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  76949. attributes: [BABYLON.VertexBuffer.PositionKind],
  76950. uniforms: ["world", "viewProjection", "color"]
  76951. });
  76952. var engine = this._scene.getEngine();
  76953. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  76954. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  76955. this._createIndexBuffer();
  76956. };
  76957. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  76958. var engine = this._scene.getEngine();
  76959. 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]);
  76960. };
  76961. BoundingBoxRenderer.prototype._rebuild = function () {
  76962. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76963. if (vb) {
  76964. vb._rebuild();
  76965. }
  76966. this._createIndexBuffer();
  76967. };
  76968. BoundingBoxRenderer.prototype.reset = function () {
  76969. this.renderList.reset();
  76970. };
  76971. BoundingBoxRenderer.prototype.render = function () {
  76972. if (this.renderList.length === 0) {
  76973. return;
  76974. }
  76975. this._prepareRessources();
  76976. if (!this._colorShader.isReady()) {
  76977. return;
  76978. }
  76979. var engine = this._scene.getEngine();
  76980. engine.setDepthWrite(false);
  76981. this._colorShader._preBind();
  76982. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  76983. var boundingBox = this.renderList.data[boundingBoxIndex];
  76984. var min = boundingBox.minimum;
  76985. var max = boundingBox.maximum;
  76986. var diff = max.subtract(min);
  76987. var median = min.add(diff.scale(0.5));
  76988. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76989. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76990. .multiply(boundingBox.getWorldMatrix());
  76991. // VBOs
  76992. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76993. if (this.showBackLines) {
  76994. // Back
  76995. engine.setDepthFunctionToGreaterOrEqual();
  76996. this._scene.resetCachedMaterial();
  76997. this._colorShader.setColor4("color", this.backColor.toColor4());
  76998. this._colorShader.bind(worldMatrix);
  76999. // Draw order
  77000. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77001. }
  77002. // Front
  77003. engine.setDepthFunctionToLess();
  77004. this._scene.resetCachedMaterial();
  77005. this._colorShader.setColor4("color", this.frontColor.toColor4());
  77006. this._colorShader.bind(worldMatrix);
  77007. // Draw order
  77008. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77009. }
  77010. this._colorShader.unbind();
  77011. engine.setDepthFunctionToLessOrEqual();
  77012. engine.setDepthWrite(true);
  77013. };
  77014. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  77015. this._prepareRessources();
  77016. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  77017. return;
  77018. }
  77019. var engine = this._scene.getEngine();
  77020. engine.setDepthWrite(false);
  77021. engine.setColorWrite(false);
  77022. this._colorShader._preBind();
  77023. var boundingBox = mesh._boundingInfo.boundingBox;
  77024. var min = boundingBox.minimum;
  77025. var max = boundingBox.maximum;
  77026. var diff = max.subtract(min);
  77027. var median = min.add(diff.scale(0.5));
  77028. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  77029. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  77030. .multiply(boundingBox.getWorldMatrix());
  77031. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  77032. engine.setDepthFunctionToLess();
  77033. this._scene.resetCachedMaterial();
  77034. this._colorShader.bind(worldMatrix);
  77035. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77036. this._colorShader.unbind();
  77037. engine.setDepthFunctionToLessOrEqual();
  77038. engine.setDepthWrite(true);
  77039. engine.setColorWrite(true);
  77040. };
  77041. BoundingBoxRenderer.prototype.dispose = function () {
  77042. if (!this._colorShader) {
  77043. return;
  77044. }
  77045. this.renderList.dispose();
  77046. this._colorShader.dispose();
  77047. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77048. if (buffer) {
  77049. buffer.dispose();
  77050. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77051. }
  77052. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77053. };
  77054. return BoundingBoxRenderer;
  77055. }());
  77056. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  77057. })(BABYLON || (BABYLON = {}));
  77058. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  77059. var BABYLON;
  77060. (function (BABYLON) {
  77061. var MorphTarget = /** @class */ (function () {
  77062. function MorphTarget(name, influence) {
  77063. if (influence === void 0) { influence = 0; }
  77064. this.name = name;
  77065. this.animations = new Array();
  77066. this._positions = null;
  77067. this._normals = null;
  77068. this._tangents = null;
  77069. this.onInfluenceChanged = new BABYLON.Observable();
  77070. this.influence = influence;
  77071. }
  77072. Object.defineProperty(MorphTarget.prototype, "influence", {
  77073. get: function () {
  77074. return this._influence;
  77075. },
  77076. set: function (influence) {
  77077. if (this._influence === influence) {
  77078. return;
  77079. }
  77080. var previous = this._influence;
  77081. this._influence = influence;
  77082. if (this.onInfluenceChanged.hasObservers) {
  77083. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  77084. }
  77085. },
  77086. enumerable: true,
  77087. configurable: true
  77088. });
  77089. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  77090. get: function () {
  77091. return !!this._positions;
  77092. },
  77093. enumerable: true,
  77094. configurable: true
  77095. });
  77096. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  77097. get: function () {
  77098. return !!this._normals;
  77099. },
  77100. enumerable: true,
  77101. configurable: true
  77102. });
  77103. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  77104. get: function () {
  77105. return !!this._tangents;
  77106. },
  77107. enumerable: true,
  77108. configurable: true
  77109. });
  77110. MorphTarget.prototype.setPositions = function (data) {
  77111. this._positions = data;
  77112. };
  77113. MorphTarget.prototype.getPositions = function () {
  77114. return this._positions;
  77115. };
  77116. MorphTarget.prototype.setNormals = function (data) {
  77117. this._normals = data;
  77118. };
  77119. MorphTarget.prototype.getNormals = function () {
  77120. return this._normals;
  77121. };
  77122. MorphTarget.prototype.setTangents = function (data) {
  77123. this._tangents = data;
  77124. };
  77125. MorphTarget.prototype.getTangents = function () {
  77126. return this._tangents;
  77127. };
  77128. /**
  77129. * Serializes the current target into a Serialization object.
  77130. * Returns the serialized object.
  77131. */
  77132. MorphTarget.prototype.serialize = function () {
  77133. var serializationObject = {};
  77134. serializationObject.name = this.name;
  77135. serializationObject.influence = this.influence;
  77136. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  77137. if (this.hasNormals) {
  77138. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  77139. }
  77140. if (this.hasTangents) {
  77141. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  77142. }
  77143. // Animations
  77144. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  77145. return serializationObject;
  77146. };
  77147. // Statics
  77148. MorphTarget.Parse = function (serializationObject) {
  77149. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  77150. result.setPositions(serializationObject.positions);
  77151. if (serializationObject.normals) {
  77152. result.setNormals(serializationObject.normals);
  77153. }
  77154. if (serializationObject.tangents) {
  77155. result.setTangents(serializationObject.tangents);
  77156. }
  77157. // Animations
  77158. if (serializationObject.animations) {
  77159. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  77160. var parsedAnimation = serializationObject.animations[animationIndex];
  77161. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  77162. }
  77163. }
  77164. return result;
  77165. };
  77166. MorphTarget.FromMesh = function (mesh, name, influence) {
  77167. if (!name) {
  77168. name = mesh.name;
  77169. }
  77170. var result = new MorphTarget(name, influence);
  77171. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77172. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77173. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  77174. }
  77175. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  77176. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  77177. }
  77178. return result;
  77179. };
  77180. return MorphTarget;
  77181. }());
  77182. BABYLON.MorphTarget = MorphTarget;
  77183. })(BABYLON || (BABYLON = {}));
  77184. //# sourceMappingURL=babylon.morphTarget.js.map
  77185. var BABYLON;
  77186. (function (BABYLON) {
  77187. var MorphTargetManager = /** @class */ (function () {
  77188. function MorphTargetManager(scene) {
  77189. if (scene === void 0) { scene = null; }
  77190. this._targets = new Array();
  77191. this._targetObservable = new Array();
  77192. this._activeTargets = new BABYLON.SmartArray(16);
  77193. this._supportsNormals = false;
  77194. this._supportsTangents = false;
  77195. this._vertexCount = 0;
  77196. this._uniqueId = 0;
  77197. this._tempInfluences = new Array();
  77198. if (!scene) {
  77199. scene = BABYLON.Engine.LastCreatedScene;
  77200. }
  77201. this._scene = scene;
  77202. if (this._scene) {
  77203. this._scene.morphTargetManagers.push(this);
  77204. this._uniqueId = this._scene.getUniqueId();
  77205. }
  77206. }
  77207. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  77208. get: function () {
  77209. return this._uniqueId;
  77210. },
  77211. enumerable: true,
  77212. configurable: true
  77213. });
  77214. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  77215. get: function () {
  77216. return this._vertexCount;
  77217. },
  77218. enumerable: true,
  77219. configurable: true
  77220. });
  77221. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  77222. get: function () {
  77223. return this._supportsNormals;
  77224. },
  77225. enumerable: true,
  77226. configurable: true
  77227. });
  77228. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  77229. get: function () {
  77230. return this._supportsTangents;
  77231. },
  77232. enumerable: true,
  77233. configurable: true
  77234. });
  77235. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  77236. get: function () {
  77237. return this._targets.length;
  77238. },
  77239. enumerable: true,
  77240. configurable: true
  77241. });
  77242. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  77243. get: function () {
  77244. return this._activeTargets.length;
  77245. },
  77246. enumerable: true,
  77247. configurable: true
  77248. });
  77249. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  77250. get: function () {
  77251. return this._influences;
  77252. },
  77253. enumerable: true,
  77254. configurable: true
  77255. });
  77256. MorphTargetManager.prototype.getActiveTarget = function (index) {
  77257. return this._activeTargets.data[index];
  77258. };
  77259. MorphTargetManager.prototype.getTarget = function (index) {
  77260. return this._targets[index];
  77261. };
  77262. MorphTargetManager.prototype.addTarget = function (target) {
  77263. var _this = this;
  77264. this._targets.push(target);
  77265. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  77266. _this._syncActiveTargets(needUpdate);
  77267. }));
  77268. this._syncActiveTargets(true);
  77269. };
  77270. MorphTargetManager.prototype.removeTarget = function (target) {
  77271. var index = this._targets.indexOf(target);
  77272. if (index >= 0) {
  77273. this._targets.splice(index, 1);
  77274. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  77275. this._syncActiveTargets(true);
  77276. }
  77277. };
  77278. /**
  77279. * Serializes the current manager into a Serialization object.
  77280. * Returns the serialized object.
  77281. */
  77282. MorphTargetManager.prototype.serialize = function () {
  77283. var serializationObject = {};
  77284. serializationObject.id = this.uniqueId;
  77285. serializationObject.targets = [];
  77286. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77287. var target = _a[_i];
  77288. serializationObject.targets.push(target.serialize());
  77289. }
  77290. return serializationObject;
  77291. };
  77292. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  77293. var influenceCount = 0;
  77294. this._activeTargets.reset();
  77295. this._supportsNormals = true;
  77296. this._supportsTangents = true;
  77297. this._vertexCount = 0;
  77298. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77299. var target = _a[_i];
  77300. this._activeTargets.push(target);
  77301. this._tempInfluences[influenceCount++] = target.influence;
  77302. var positions = target.getPositions();
  77303. if (positions) {
  77304. this._supportsNormals = this._supportsNormals && target.hasNormals;
  77305. this._supportsTangents = this._supportsTangents && target.hasTangents;
  77306. var vertexCount = positions.length / 3;
  77307. if (this._vertexCount === 0) {
  77308. this._vertexCount = vertexCount;
  77309. }
  77310. else if (this._vertexCount !== vertexCount) {
  77311. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  77312. return;
  77313. }
  77314. }
  77315. }
  77316. if (!this._influences || this._influences.length !== influenceCount) {
  77317. this._influences = new Float32Array(influenceCount);
  77318. }
  77319. for (var index = 0; index < influenceCount; index++) {
  77320. this._influences[index] = this._tempInfluences[index];
  77321. }
  77322. if (needUpdate && this._scene) {
  77323. // Flag meshes as dirty to resync with the active targets
  77324. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  77325. var mesh = _c[_b];
  77326. if (mesh.morphTargetManager === this) {
  77327. mesh._syncGeometryWithMorphTargetManager();
  77328. }
  77329. }
  77330. }
  77331. };
  77332. // Statics
  77333. MorphTargetManager.Parse = function (serializationObject, scene) {
  77334. var result = new MorphTargetManager(scene);
  77335. result._uniqueId = serializationObject.id;
  77336. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  77337. var targetData = _a[_i];
  77338. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  77339. }
  77340. return result;
  77341. };
  77342. return MorphTargetManager;
  77343. }());
  77344. BABYLON.MorphTargetManager = MorphTargetManager;
  77345. })(BABYLON || (BABYLON = {}));
  77346. //# sourceMappingURL=babylon.morphTargetManager.js.map
  77347. var BABYLON;
  77348. (function (BABYLON) {
  77349. var Octree = /** @class */ (function () {
  77350. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  77351. if (maxDepth === void 0) { maxDepth = 2; }
  77352. this.maxDepth = maxDepth;
  77353. this.dynamicContent = new Array();
  77354. this._maxBlockCapacity = maxBlockCapacity || 64;
  77355. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  77356. this._creationFunc = creationFunc;
  77357. }
  77358. // Methods
  77359. Octree.prototype.update = function (worldMin, worldMax, entries) {
  77360. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  77361. };
  77362. Octree.prototype.addMesh = function (entry) {
  77363. for (var index = 0; index < this.blocks.length; index++) {
  77364. var block = this.blocks[index];
  77365. block.addEntry(entry);
  77366. }
  77367. };
  77368. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  77369. this._selectionContent.reset();
  77370. for (var index = 0; index < this.blocks.length; index++) {
  77371. var block = this.blocks[index];
  77372. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  77373. }
  77374. if (allowDuplicate) {
  77375. this._selectionContent.concat(this.dynamicContent);
  77376. }
  77377. else {
  77378. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77379. }
  77380. return this._selectionContent;
  77381. };
  77382. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  77383. this._selectionContent.reset();
  77384. for (var index = 0; index < this.blocks.length; index++) {
  77385. var block = this.blocks[index];
  77386. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  77387. }
  77388. if (allowDuplicate) {
  77389. this._selectionContent.concat(this.dynamicContent);
  77390. }
  77391. else {
  77392. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77393. }
  77394. return this._selectionContent;
  77395. };
  77396. Octree.prototype.intersectsRay = function (ray) {
  77397. this._selectionContent.reset();
  77398. for (var index = 0; index < this.blocks.length; index++) {
  77399. var block = this.blocks[index];
  77400. block.intersectsRay(ray, this._selectionContent);
  77401. }
  77402. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77403. return this._selectionContent;
  77404. };
  77405. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  77406. target.blocks = new Array();
  77407. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  77408. // Segmenting space
  77409. for (var x = 0; x < 2; x++) {
  77410. for (var y = 0; y < 2; y++) {
  77411. for (var z = 0; z < 2; z++) {
  77412. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  77413. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  77414. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  77415. block.addEntries(entries);
  77416. target.blocks.push(block);
  77417. }
  77418. }
  77419. }
  77420. };
  77421. Octree.CreationFuncForMeshes = function (entry, block) {
  77422. var boundingInfo = entry.getBoundingInfo();
  77423. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77424. block.entries.push(entry);
  77425. }
  77426. };
  77427. Octree.CreationFuncForSubMeshes = function (entry, block) {
  77428. var boundingInfo = entry.getBoundingInfo();
  77429. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77430. block.entries.push(entry);
  77431. }
  77432. };
  77433. return Octree;
  77434. }());
  77435. BABYLON.Octree = Octree;
  77436. })(BABYLON || (BABYLON = {}));
  77437. //# sourceMappingURL=babylon.octree.js.map
  77438. var BABYLON;
  77439. (function (BABYLON) {
  77440. var OctreeBlock = /** @class */ (function () {
  77441. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  77442. this.entries = new Array();
  77443. this._boundingVectors = new Array();
  77444. this._capacity = capacity;
  77445. this._depth = depth;
  77446. this._maxDepth = maxDepth;
  77447. this._creationFunc = creationFunc;
  77448. this._minPoint = minPoint;
  77449. this._maxPoint = maxPoint;
  77450. this._boundingVectors.push(minPoint.clone());
  77451. this._boundingVectors.push(maxPoint.clone());
  77452. this._boundingVectors.push(minPoint.clone());
  77453. this._boundingVectors[2].x = maxPoint.x;
  77454. this._boundingVectors.push(minPoint.clone());
  77455. this._boundingVectors[3].y = maxPoint.y;
  77456. this._boundingVectors.push(minPoint.clone());
  77457. this._boundingVectors[4].z = maxPoint.z;
  77458. this._boundingVectors.push(maxPoint.clone());
  77459. this._boundingVectors[5].z = minPoint.z;
  77460. this._boundingVectors.push(maxPoint.clone());
  77461. this._boundingVectors[6].x = minPoint.x;
  77462. this._boundingVectors.push(maxPoint.clone());
  77463. this._boundingVectors[7].y = minPoint.y;
  77464. }
  77465. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  77466. // Property
  77467. get: function () {
  77468. return this._capacity;
  77469. },
  77470. enumerable: true,
  77471. configurable: true
  77472. });
  77473. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  77474. get: function () {
  77475. return this._minPoint;
  77476. },
  77477. enumerable: true,
  77478. configurable: true
  77479. });
  77480. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  77481. get: function () {
  77482. return this._maxPoint;
  77483. },
  77484. enumerable: true,
  77485. configurable: true
  77486. });
  77487. // Methods
  77488. OctreeBlock.prototype.addEntry = function (entry) {
  77489. if (this.blocks) {
  77490. for (var index = 0; index < this.blocks.length; index++) {
  77491. var block = this.blocks[index];
  77492. block.addEntry(entry);
  77493. }
  77494. return;
  77495. }
  77496. this._creationFunc(entry, this);
  77497. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  77498. this.createInnerBlocks();
  77499. }
  77500. };
  77501. OctreeBlock.prototype.addEntries = function (entries) {
  77502. for (var index = 0; index < entries.length; index++) {
  77503. var mesh = entries[index];
  77504. this.addEntry(mesh);
  77505. }
  77506. };
  77507. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  77508. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  77509. if (this.blocks) {
  77510. for (var index = 0; index < this.blocks.length; index++) {
  77511. var block = this.blocks[index];
  77512. block.select(frustumPlanes, selection, allowDuplicate);
  77513. }
  77514. return;
  77515. }
  77516. if (allowDuplicate) {
  77517. selection.concat(this.entries);
  77518. }
  77519. else {
  77520. selection.concatWithNoDuplicate(this.entries);
  77521. }
  77522. }
  77523. };
  77524. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  77525. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  77526. if (this.blocks) {
  77527. for (var index = 0; index < this.blocks.length; index++) {
  77528. var block = this.blocks[index];
  77529. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  77530. }
  77531. return;
  77532. }
  77533. if (allowDuplicate) {
  77534. selection.concat(this.entries);
  77535. }
  77536. else {
  77537. selection.concatWithNoDuplicate(this.entries);
  77538. }
  77539. }
  77540. };
  77541. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  77542. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  77543. if (this.blocks) {
  77544. for (var index = 0; index < this.blocks.length; index++) {
  77545. var block = this.blocks[index];
  77546. block.intersectsRay(ray, selection);
  77547. }
  77548. return;
  77549. }
  77550. selection.concatWithNoDuplicate(this.entries);
  77551. }
  77552. };
  77553. OctreeBlock.prototype.createInnerBlocks = function () {
  77554. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  77555. };
  77556. return OctreeBlock;
  77557. }());
  77558. BABYLON.OctreeBlock = OctreeBlock;
  77559. })(BABYLON || (BABYLON = {}));
  77560. //# sourceMappingURL=babylon.octreeBlock.js.map
  77561. var BABYLON;
  77562. (function (BABYLON) {
  77563. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  77564. __extends(VRDistortionCorrectionPostProcess, _super);
  77565. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  77566. var _this = _super.call(this, name, "vrDistortionCorrection", [
  77567. 'LensCenter',
  77568. 'Scale',
  77569. 'ScaleIn',
  77570. 'HmdWarpParam'
  77571. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  77572. _this._isRightEye = isRightEye;
  77573. _this._distortionFactors = vrMetrics.distortionK;
  77574. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  77575. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  77576. _this.adaptScaleToCurrentViewport = true;
  77577. _this.onSizeChangedObservable.add(function () {
  77578. _this.aspectRatio = _this.width * .5 / _this.height;
  77579. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  77580. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  77581. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  77582. });
  77583. _this.onApplyObservable.add(function (effect) {
  77584. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  77585. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  77586. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  77587. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  77588. });
  77589. return _this;
  77590. }
  77591. return VRDistortionCorrectionPostProcess;
  77592. }(BABYLON.PostProcess));
  77593. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  77594. })(BABYLON || (BABYLON = {}));
  77595. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  77596. var BABYLON;
  77597. (function (BABYLON) {
  77598. var AnaglyphPostProcess = /** @class */ (function (_super) {
  77599. __extends(AnaglyphPostProcess, _super);
  77600. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  77601. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  77602. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77603. _this.onApplyObservable.add(function (effect) {
  77604. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  77605. });
  77606. return _this;
  77607. }
  77608. return AnaglyphPostProcess;
  77609. }(BABYLON.PostProcess));
  77610. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  77611. })(BABYLON || (BABYLON = {}));
  77612. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  77613. var BABYLON;
  77614. (function (BABYLON) {
  77615. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  77616. __extends(StereoscopicInterlacePostProcess, _super);
  77617. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  77618. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  77619. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77620. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77621. _this.onSizeChangedObservable.add(function () {
  77622. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77623. });
  77624. _this.onApplyObservable.add(function (effect) {
  77625. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  77626. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  77627. });
  77628. return _this;
  77629. }
  77630. return StereoscopicInterlacePostProcess;
  77631. }(BABYLON.PostProcess));
  77632. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  77633. })(BABYLON || (BABYLON = {}));
  77634. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  77635. var BABYLON;
  77636. (function (BABYLON) {
  77637. /**
  77638. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  77639. * Screen rotation is taken into account.
  77640. */
  77641. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  77642. function FreeCameraDeviceOrientationInput() {
  77643. var _this = this;
  77644. this._screenOrientationAngle = 0;
  77645. this._screenQuaternion = new BABYLON.Quaternion();
  77646. this._alpha = 0;
  77647. this._beta = 0;
  77648. this._gamma = 0;
  77649. this._orientationChanged = function () {
  77650. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  77651. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  77652. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  77653. };
  77654. this._deviceOrientation = function (evt) {
  77655. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  77656. _this._beta = evt.beta !== null ? evt.beta : 0;
  77657. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  77658. };
  77659. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  77660. this._orientationChanged();
  77661. }
  77662. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  77663. get: function () {
  77664. return this._camera;
  77665. },
  77666. set: function (camera) {
  77667. this._camera = camera;
  77668. if (this._camera != null && !this._camera.rotationQuaternion) {
  77669. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  77670. }
  77671. },
  77672. enumerable: true,
  77673. configurable: true
  77674. });
  77675. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77676. window.addEventListener("orientationchange", this._orientationChanged);
  77677. window.addEventListener("deviceorientation", this._deviceOrientation);
  77678. //In certain cases, the attach control is called AFTER orientation was changed,
  77679. //So this is needed.
  77680. this._orientationChanged();
  77681. };
  77682. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  77683. window.removeEventListener("orientationchange", this._orientationChanged);
  77684. window.removeEventListener("deviceorientation", this._deviceOrientation);
  77685. };
  77686. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  77687. //if no device orientation provided, don't update the rotation.
  77688. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  77689. if (!this._alpha)
  77690. return;
  77691. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  77692. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  77693. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  77694. //Mirror on XY Plane
  77695. this._camera.rotationQuaternion.z *= -1;
  77696. this._camera.rotationQuaternion.w *= -1;
  77697. };
  77698. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  77699. return "FreeCameraDeviceOrientationInput";
  77700. };
  77701. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  77702. return "deviceOrientation";
  77703. };
  77704. return FreeCameraDeviceOrientationInput;
  77705. }());
  77706. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  77707. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  77708. })(BABYLON || (BABYLON = {}));
  77709. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  77710. var BABYLON;
  77711. (function (BABYLON) {
  77712. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  77713. function ArcRotateCameraVRDeviceOrientationInput() {
  77714. this.alphaCorrection = 1;
  77715. this.betaCorrection = 1;
  77716. this.gammaCorrection = 1;
  77717. this._alpha = 0;
  77718. this._gamma = 0;
  77719. this._dirty = false;
  77720. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  77721. }
  77722. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77723. this.camera.attachControl(element, noPreventDefault);
  77724. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  77725. };
  77726. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  77727. if (evt.alpha !== null) {
  77728. this._alpha = +evt.alpha | 0;
  77729. }
  77730. if (evt.gamma !== null) {
  77731. this._gamma = +evt.gamma | 0;
  77732. }
  77733. this._dirty = true;
  77734. };
  77735. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  77736. if (this._dirty) {
  77737. this._dirty = false;
  77738. if (this._gamma < 0) {
  77739. this._gamma = 180 + this._gamma;
  77740. }
  77741. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  77742. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  77743. }
  77744. };
  77745. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  77746. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  77747. };
  77748. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  77749. return "ArcRotateCameraVRDeviceOrientationInput";
  77750. };
  77751. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  77752. return "VRDeviceOrientation";
  77753. };
  77754. return ArcRotateCameraVRDeviceOrientationInput;
  77755. }());
  77756. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  77757. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  77758. })(BABYLON || (BABYLON = {}));
  77759. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  77760. var BABYLON;
  77761. (function (BABYLON) {
  77762. var VRCameraMetrics = /** @class */ (function () {
  77763. function VRCameraMetrics() {
  77764. this.compensateDistortion = true;
  77765. }
  77766. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  77767. get: function () {
  77768. return this.hResolution / (2 * this.vResolution);
  77769. },
  77770. enumerable: true,
  77771. configurable: true
  77772. });
  77773. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  77774. get: function () {
  77775. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  77776. },
  77777. enumerable: true,
  77778. configurable: true
  77779. });
  77780. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  77781. get: function () {
  77782. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77783. var h = (4 * meters) / this.hScreenSize;
  77784. return BABYLON.Matrix.Translation(h, 0, 0);
  77785. },
  77786. enumerable: true,
  77787. configurable: true
  77788. });
  77789. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  77790. get: function () {
  77791. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77792. var h = (4 * meters) / this.hScreenSize;
  77793. return BABYLON.Matrix.Translation(-h, 0, 0);
  77794. },
  77795. enumerable: true,
  77796. configurable: true
  77797. });
  77798. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  77799. get: function () {
  77800. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  77801. },
  77802. enumerable: true,
  77803. configurable: true
  77804. });
  77805. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  77806. get: function () {
  77807. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  77808. },
  77809. enumerable: true,
  77810. configurable: true
  77811. });
  77812. VRCameraMetrics.GetDefault = function () {
  77813. var result = new VRCameraMetrics();
  77814. result.hResolution = 1280;
  77815. result.vResolution = 800;
  77816. result.hScreenSize = 0.149759993;
  77817. result.vScreenSize = 0.0935999975;
  77818. result.vScreenCenter = 0.0467999987;
  77819. result.eyeToScreenDistance = 0.0410000011;
  77820. result.lensSeparationDistance = 0.0635000020;
  77821. result.interpupillaryDistance = 0.0640000030;
  77822. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  77823. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  77824. result.postProcessScaleFactor = 1.714605507808412;
  77825. result.lensCenterOffset = 0.151976421;
  77826. return result;
  77827. };
  77828. return VRCameraMetrics;
  77829. }());
  77830. BABYLON.VRCameraMetrics = VRCameraMetrics;
  77831. })(BABYLON || (BABYLON = {}));
  77832. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  77833. var BABYLON;
  77834. (function (BABYLON) {
  77835. /**
  77836. * This represents a WebVR camera.
  77837. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  77838. * @example http://doc.babylonjs.com/how_to/webvr_camera
  77839. */
  77840. var WebVRFreeCamera = /** @class */ (function (_super) {
  77841. __extends(WebVRFreeCamera, _super);
  77842. /**
  77843. * Instantiates a WebVRFreeCamera.
  77844. * @param name The name of the WebVRFreeCamera
  77845. * @param position The starting anchor position for the camera
  77846. * @param scene The scene the camera belongs to
  77847. * @param webVROptions a set of customizable options for the webVRCamera
  77848. */
  77849. function WebVRFreeCamera(name, position, scene, webVROptions) {
  77850. if (webVROptions === void 0) { webVROptions = {}; }
  77851. var _this = _super.call(this, name, position, scene) || this;
  77852. _this.webVROptions = webVROptions;
  77853. /**
  77854. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  77855. */
  77856. _this._vrDevice = null;
  77857. /**
  77858. * The rawPose of the vrDevice.
  77859. */
  77860. _this.rawPose = null;
  77861. _this._specsVersion = "1.1";
  77862. _this._attached = false;
  77863. _this._descendants = [];
  77864. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  77865. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  77866. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  77867. _this._standingMatrix = null;
  77868. /**
  77869. * Represents device position in babylon space.
  77870. */
  77871. _this.devicePosition = BABYLON.Vector3.Zero();
  77872. /**
  77873. * Represents device rotation in babylon space.
  77874. */
  77875. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  77876. /**
  77877. * The scale of the device to be used when translating from device space to babylon space.
  77878. */
  77879. _this.deviceScaleFactor = 1;
  77880. _this._deviceToWorld = BABYLON.Matrix.Identity();
  77881. _this._worldToDevice = BABYLON.Matrix.Identity();
  77882. /**
  77883. * References to the webVR controllers for the vrDevice.
  77884. */
  77885. _this.controllers = [];
  77886. /**
  77887. * Emits an event when a controller is attached.
  77888. */
  77889. _this.onControllersAttachedObservable = new BABYLON.Observable();
  77890. /**
  77891. * Emits an event when a controller's mesh has been loaded;
  77892. */
  77893. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  77894. /**
  77895. * If the rig cameras be used as parent instead of this camera.
  77896. */
  77897. _this.rigParenting = true;
  77898. _this._defaultHeight = undefined;
  77899. _this._workingVector = BABYLON.Vector3.Zero();
  77900. _this._oneVector = BABYLON.Vector3.One();
  77901. _this._workingMatrix = BABYLON.Matrix.Identity();
  77902. _this._cache.position = BABYLON.Vector3.Zero();
  77903. if (webVROptions.defaultHeight) {
  77904. _this._defaultHeight = webVROptions.defaultHeight;
  77905. _this.position.y = _this._defaultHeight;
  77906. }
  77907. _this.minZ = 0.1;
  77908. //legacy support - the compensation boolean was removed.
  77909. if (arguments.length === 5) {
  77910. _this.webVROptions = arguments[4];
  77911. }
  77912. // default webVR options
  77913. if (_this.webVROptions.trackPosition == undefined) {
  77914. _this.webVROptions.trackPosition = true;
  77915. }
  77916. if (_this.webVROptions.controllerMeshes == undefined) {
  77917. _this.webVROptions.controllerMeshes = true;
  77918. }
  77919. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  77920. _this.webVROptions.defaultLightingOnControllers = true;
  77921. }
  77922. _this.rotationQuaternion = new BABYLON.Quaternion();
  77923. if (_this.webVROptions && _this.webVROptions.positionScale) {
  77924. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  77925. }
  77926. //enable VR
  77927. var engine = _this.getEngine();
  77928. _this._onVREnabled = function (success) { if (success) {
  77929. _this.initControllers();
  77930. } };
  77931. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  77932. engine.initWebVR().add(function (event) {
  77933. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  77934. return;
  77935. }
  77936. _this._vrDevice = event.vrDisplay;
  77937. //reset the rig parameters.
  77938. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  77939. if (_this._attached) {
  77940. _this.getEngine().enableVR();
  77941. }
  77942. });
  77943. if (typeof (VRFrameData) !== "undefined")
  77944. _this._frameData = new VRFrameData();
  77945. /**
  77946. * The idea behind the following lines:
  77947. * objects that have the camera as parent should actually have the rig cameras as a parent.
  77948. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  77949. * the second will not show it correctly.
  77950. *
  77951. * To solve this - each object that has the camera as parent will be added to a protected array.
  77952. * When the rig camera renders, it will take this array and set all of those to be its children.
  77953. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  77954. * Amazing!
  77955. */
  77956. scene.onBeforeCameraRenderObservable.add(function (camera) {
  77957. if (camera.parent === _this && _this.rigParenting) {
  77958. _this._descendants = _this.getDescendants(true, function (n) {
  77959. // don't take the cameras or the controllers!
  77960. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  77961. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  77962. return !isController && !isRigCamera;
  77963. });
  77964. _this._descendants.forEach(function (node) {
  77965. node.parent = camera;
  77966. });
  77967. }
  77968. });
  77969. scene.onAfterCameraRenderObservable.add(function (camera) {
  77970. if (camera.parent === _this && _this.rigParenting) {
  77971. _this._descendants.forEach(function (node) {
  77972. node.parent = _this;
  77973. });
  77974. }
  77975. });
  77976. return _this;
  77977. }
  77978. /**
  77979. * Gets the device distance from the ground.
  77980. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  77981. */
  77982. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  77983. if (this._standingMatrix && this._defaultHeight === undefined) {
  77984. // Add standing matrix offset to get real offset from ground in room
  77985. this._standingMatrix.getTranslationToRef(this._workingVector);
  77986. return this._deviceRoomPosition.y + this._workingVector.y;
  77987. }
  77988. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  77989. return this._defaultHeight || 0;
  77990. };
  77991. /**
  77992. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  77993. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  77994. */
  77995. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  77996. var _this = this;
  77997. if (callback === void 0) { callback = function (bool) { }; }
  77998. // Use standing matrix if available
  77999. if (!navigator || !navigator.getVRDisplays) {
  78000. callback(false);
  78001. }
  78002. else {
  78003. navigator.getVRDisplays().then(function (displays) {
  78004. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  78005. callback(false);
  78006. }
  78007. else {
  78008. _this._standingMatrix = new BABYLON.Matrix();
  78009. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  78010. if (!_this.getScene().useRightHandedSystem) {
  78011. [2, 6, 8, 9, 14].forEach(function (num) {
  78012. if (_this._standingMatrix) {
  78013. _this._standingMatrix.m[num] *= -1;
  78014. }
  78015. });
  78016. }
  78017. callback(true);
  78018. }
  78019. });
  78020. }
  78021. };
  78022. /**
  78023. * Disposes the camera
  78024. */
  78025. WebVRFreeCamera.prototype.dispose = function () {
  78026. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  78027. _super.prototype.dispose.call(this);
  78028. };
  78029. /**
  78030. * Gets a vrController by name.
  78031. * @param name The name of the controller to retreive
  78032. * @returns the controller matching the name specified or null if not found
  78033. */
  78034. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  78035. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  78036. var gp = _a[_i];
  78037. if (gp.hand === name) {
  78038. return gp;
  78039. }
  78040. }
  78041. return null;
  78042. };
  78043. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  78044. /**
  78045. * The controller corrisponding to the users left hand.
  78046. */
  78047. get: function () {
  78048. if (!this._leftController) {
  78049. this._leftController = this.getControllerByName("left");
  78050. }
  78051. return this._leftController;
  78052. },
  78053. enumerable: true,
  78054. configurable: true
  78055. });
  78056. ;
  78057. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  78058. /**
  78059. * The controller corrisponding to the users right hand.
  78060. */
  78061. get: function () {
  78062. if (!this._rightController) {
  78063. this._rightController = this.getControllerByName("right");
  78064. }
  78065. return this._rightController;
  78066. },
  78067. enumerable: true,
  78068. configurable: true
  78069. });
  78070. ;
  78071. /**
  78072. * Casts a ray forward from the vrCamera's gaze.
  78073. * @param length Length of the ray (default: 100)
  78074. * @returns the ray corrisponding to the gaze
  78075. */
  78076. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  78077. if (length === void 0) { length = 100; }
  78078. if (this.leftCamera) {
  78079. // Use left eye to avoid computation to compute center on every call
  78080. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  78081. }
  78082. else {
  78083. return _super.prototype.getForwardRay.call(this, length);
  78084. }
  78085. };
  78086. /**
  78087. * Updates the camera based on device's frame data
  78088. */
  78089. WebVRFreeCamera.prototype._checkInputs = function () {
  78090. if (this._vrDevice && this._vrDevice.isPresenting) {
  78091. this._vrDevice.getFrameData(this._frameData);
  78092. this.updateFromDevice(this._frameData.pose);
  78093. }
  78094. _super.prototype._checkInputs.call(this);
  78095. };
  78096. /**
  78097. * Updates the poseControlled values based on the input device pose.
  78098. * @param poseData Pose coming from the device
  78099. */
  78100. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  78101. if (poseData && poseData.orientation) {
  78102. this.rawPose = poseData;
  78103. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  78104. if (this.getScene().useRightHandedSystem) {
  78105. this._deviceRoomRotationQuaternion.z *= -1;
  78106. this._deviceRoomRotationQuaternion.w *= -1;
  78107. }
  78108. if (this.webVROptions.trackPosition && this.rawPose.position) {
  78109. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  78110. if (this.getScene().useRightHandedSystem) {
  78111. this._deviceRoomPosition.z *= -1;
  78112. }
  78113. }
  78114. }
  78115. };
  78116. /**
  78117. * WebVR's attach control will start broadcasting frames to the device.
  78118. * Note that in certain browsers (chrome for example) this function must be called
  78119. * within a user-interaction callback. Example:
  78120. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  78121. *
  78122. * @param element html element to attach the vrDevice to
  78123. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  78124. */
  78125. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  78126. _super.prototype.attachControl.call(this, element, noPreventDefault);
  78127. this._attached = true;
  78128. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  78129. if (this._vrDevice) {
  78130. this.getEngine().enableVR();
  78131. }
  78132. };
  78133. /**
  78134. * Detaches the camera from the html element and disables VR
  78135. *
  78136. * @param element html element to detach from
  78137. */
  78138. WebVRFreeCamera.prototype.detachControl = function (element) {
  78139. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78140. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78141. _super.prototype.detachControl.call(this, element);
  78142. this._attached = false;
  78143. this.getEngine().disableVR();
  78144. };
  78145. /**
  78146. * @returns the name of this class
  78147. */
  78148. WebVRFreeCamera.prototype.getClassName = function () {
  78149. return "WebVRFreeCamera";
  78150. };
  78151. /**
  78152. * Calls resetPose on the vrDisplay
  78153. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  78154. */
  78155. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  78156. //uses the vrDisplay's "resetPose()".
  78157. //pitch and roll won't be affected.
  78158. this._vrDevice.resetPose();
  78159. };
  78160. /**
  78161. * Updates the rig cameras (left and right eye)
  78162. */
  78163. WebVRFreeCamera.prototype._updateRigCameras = function () {
  78164. var camLeft = this._rigCameras[0];
  78165. var camRight = this._rigCameras[1];
  78166. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78167. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78168. camLeft.position.copyFrom(this._deviceRoomPosition);
  78169. camRight.position.copyFrom(this._deviceRoomPosition);
  78170. };
  78171. /**
  78172. * Updates the cached values of the camera
  78173. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  78174. */
  78175. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  78176. var _this = this;
  78177. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  78178. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  78179. if (!this.updateCacheCalled) {
  78180. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  78181. this.updateCacheCalled = true;
  78182. this.update();
  78183. }
  78184. // Set working vector to the device position in room space rotated by the new rotation
  78185. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  78186. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  78187. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  78188. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  78189. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  78190. // Add translation from anchor position
  78191. this._deviceToWorld.getTranslationToRef(this._workingVector);
  78192. this._workingVector.addInPlace(this.position);
  78193. this._workingVector.subtractInPlace(this._cache.position);
  78194. this._deviceToWorld.setTranslation(this._workingVector);
  78195. // Set an inverted matrix to be used when updating the camera
  78196. this._deviceToWorld.invertToRef(this._worldToDevice);
  78197. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  78198. this.controllers.forEach(function (controller) {
  78199. controller._deviceToWorld = _this._deviceToWorld;
  78200. controller.update();
  78201. });
  78202. }
  78203. if (!ignoreParentClass) {
  78204. _super.prototype._updateCache.call(this);
  78205. }
  78206. this.updateCacheCalled = false;
  78207. };
  78208. /**
  78209. * Updates the current device position and rotation in the babylon world
  78210. */
  78211. WebVRFreeCamera.prototype.update = function () {
  78212. // Get current device position in babylon world
  78213. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  78214. // Get current device rotation in babylon world
  78215. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  78216. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  78217. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78218. _super.prototype.update.call(this);
  78219. };
  78220. /**
  78221. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  78222. * @returns an identity matrix
  78223. */
  78224. WebVRFreeCamera.prototype._getViewMatrix = function () {
  78225. return BABYLON.Matrix.Identity();
  78226. };
  78227. /**
  78228. * This function is called by the two RIG cameras.
  78229. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  78230. */
  78231. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  78232. var _this = this;
  78233. //WebVR 1.1
  78234. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  78235. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  78236. if (!this.getScene().useRightHandedSystem) {
  78237. [2, 6, 8, 9, 14].forEach(function (num) {
  78238. _this._webvrViewMatrix.m[num] *= -1;
  78239. });
  78240. }
  78241. // update the camera rotation matrix
  78242. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  78243. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  78244. // Computing target and final matrix
  78245. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  78246. var parentCamera = this._cameraRigParams["parentCamera"];
  78247. // should the view matrix be updated with scale and position offset?
  78248. if (parentCamera.deviceScaleFactor !== 1) {
  78249. this._webvrViewMatrix.invert();
  78250. // scale the position, if set
  78251. if (parentCamera.deviceScaleFactor) {
  78252. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  78253. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  78254. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  78255. }
  78256. this._webvrViewMatrix.invert();
  78257. }
  78258. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  78259. return this._webvrViewMatrix;
  78260. };
  78261. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  78262. var _this = this;
  78263. var parentCamera = this.parent;
  78264. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  78265. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  78266. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  78267. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  78268. //babylon compatible matrix
  78269. if (!this.getScene().useRightHandedSystem) {
  78270. [8, 9, 10, 11].forEach(function (num) {
  78271. _this._projectionMatrix.m[num] *= -1;
  78272. });
  78273. }
  78274. return this._projectionMatrix;
  78275. };
  78276. /**
  78277. * Initializes the controllers and their meshes
  78278. */
  78279. WebVRFreeCamera.prototype.initControllers = function () {
  78280. var _this = this;
  78281. this.controllers = [];
  78282. var manager = this.getScene().gamepadManager;
  78283. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78284. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78285. var webVrController = gamepad;
  78286. if (webVrController.defaultModel) {
  78287. webVrController.defaultModel.setEnabled(false);
  78288. }
  78289. if (webVrController.hand === "right") {
  78290. _this._rightController = null;
  78291. }
  78292. if (webVrController.hand === "left") {
  78293. _this._rightController = null;
  78294. }
  78295. var controllerIndex = _this.controllers.indexOf(webVrController);
  78296. if (controllerIndex !== -1) {
  78297. _this.controllers.splice(controllerIndex, 1);
  78298. }
  78299. }
  78300. });
  78301. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78302. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78303. var webVrController_1 = gamepad;
  78304. webVrController_1._deviceToWorld = _this._deviceToWorld;
  78305. if (_this.webVROptions.controllerMeshes) {
  78306. if (webVrController_1.defaultModel) {
  78307. webVrController_1.defaultModel.setEnabled(true);
  78308. }
  78309. else {
  78310. // Load the meshes
  78311. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  78312. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  78313. if (_this.webVROptions.defaultLightingOnControllers) {
  78314. if (!_this._lightOnControllers) {
  78315. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  78316. }
  78317. var activateLightOnSubMeshes_1 = function (mesh, light) {
  78318. var children = mesh.getChildren();
  78319. if (children.length !== 0) {
  78320. children.forEach(function (mesh) {
  78321. light.includedOnlyMeshes.push(mesh);
  78322. activateLightOnSubMeshes_1(mesh, light);
  78323. });
  78324. }
  78325. };
  78326. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  78327. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  78328. }
  78329. });
  78330. }
  78331. }
  78332. webVrController_1.attachToPoseControlledCamera(_this);
  78333. // since this is async - sanity check. Is the controller already stored?
  78334. if (_this.controllers.indexOf(webVrController_1) === -1) {
  78335. //add to the controllers array
  78336. _this.controllers.push(webVrController_1);
  78337. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  78338. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  78339. // So we're overriding setting left & right manually to be sure
  78340. var firstViveWandDetected = false;
  78341. for (var i = 0; i < _this.controllers.length; i++) {
  78342. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  78343. if (!firstViveWandDetected) {
  78344. firstViveWandDetected = true;
  78345. _this.controllers[i].hand = "left";
  78346. }
  78347. else {
  78348. _this.controllers[i].hand = "right";
  78349. }
  78350. }
  78351. }
  78352. //did we find enough controllers? Great! let the developer know.
  78353. if (_this.controllers.length >= 2) {
  78354. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  78355. }
  78356. }
  78357. }
  78358. });
  78359. };
  78360. return WebVRFreeCamera;
  78361. }(BABYLON.FreeCamera));
  78362. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  78363. })(BABYLON || (BABYLON = {}));
  78364. //# sourceMappingURL=babylon.webVRCamera.js.map
  78365. var BABYLON;
  78366. (function (BABYLON) {
  78367. // We're mainly based on the logic defined into the FreeCamera code
  78368. /**
  78369. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  78370. * being tilted forward or back and left or right.
  78371. */
  78372. var DeviceOrientationCamera = /** @class */ (function (_super) {
  78373. __extends(DeviceOrientationCamera, _super);
  78374. /**
  78375. * Creates a new device orientation camera. @see DeviceOrientationCamera
  78376. * @param name The name of the camera
  78377. * @param position The start position camera
  78378. * @param scene The scene the camera belongs to
  78379. */
  78380. function DeviceOrientationCamera(name, position, scene) {
  78381. var _this = _super.call(this, name, position, scene) || this;
  78382. _this._quaternionCache = new BABYLON.Quaternion();
  78383. _this.inputs.addDeviceOrientation();
  78384. return _this;
  78385. }
  78386. /**
  78387. * Gets the current instance class name ("DeviceOrientationCamera").
  78388. * This helps avoiding instanceof at run time.
  78389. * @returns the class name
  78390. */
  78391. DeviceOrientationCamera.prototype.getClassName = function () {
  78392. return "DeviceOrientationCamera";
  78393. };
  78394. /**
  78395. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  78396. */
  78397. DeviceOrientationCamera.prototype._checkInputs = function () {
  78398. _super.prototype._checkInputs.call(this);
  78399. this._quaternionCache.copyFrom(this.rotationQuaternion);
  78400. if (this._initialQuaternion) {
  78401. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78402. }
  78403. };
  78404. /**
  78405. * Reset the camera to its default orientation on the specified axis only.
  78406. * @param axis The axis to reset
  78407. */
  78408. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  78409. var _this = this;
  78410. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  78411. //can only work if this camera has a rotation quaternion already.
  78412. if (!this.rotationQuaternion)
  78413. return;
  78414. if (!this._initialQuaternion) {
  78415. this._initialQuaternion = new BABYLON.Quaternion();
  78416. }
  78417. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  78418. ['x', 'y', 'z'].forEach(function (axisName) {
  78419. if (!axis[axisName]) {
  78420. _this._initialQuaternion[axisName] = 0;
  78421. }
  78422. else {
  78423. _this._initialQuaternion[axisName] *= -1;
  78424. }
  78425. });
  78426. this._initialQuaternion.normalize();
  78427. //force rotation update
  78428. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78429. };
  78430. return DeviceOrientationCamera;
  78431. }(BABYLON.FreeCamera));
  78432. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  78433. })(BABYLON || (BABYLON = {}));
  78434. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  78435. var BABYLON;
  78436. (function (BABYLON) {
  78437. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  78438. __extends(VRDeviceOrientationFreeCamera, _super);
  78439. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78440. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78441. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78442. var _this = _super.call(this, name, position, scene) || this;
  78443. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78444. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78445. return _this;
  78446. }
  78447. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  78448. return "VRDeviceOrientationFreeCamera";
  78449. };
  78450. return VRDeviceOrientationFreeCamera;
  78451. }(BABYLON.DeviceOrientationCamera));
  78452. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  78453. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  78454. __extends(VRDeviceOrientationGamepadCamera, _super);
  78455. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78456. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78457. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78458. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  78459. _this.inputs.addGamepad();
  78460. return _this;
  78461. }
  78462. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  78463. return "VRDeviceOrientationGamepadCamera";
  78464. };
  78465. return VRDeviceOrientationGamepadCamera;
  78466. }(VRDeviceOrientationFreeCamera));
  78467. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  78468. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  78469. __extends(VRDeviceOrientationArcRotateCamera, _super);
  78470. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  78471. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78472. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78473. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78474. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78475. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78476. _this.inputs.addVRDeviceOrientation();
  78477. return _this;
  78478. }
  78479. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  78480. return "VRDeviceOrientationArcRotateCamera";
  78481. };
  78482. return VRDeviceOrientationArcRotateCamera;
  78483. }(BABYLON.ArcRotateCamera));
  78484. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  78485. })(BABYLON || (BABYLON = {}));
  78486. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  78487. var BABYLON;
  78488. (function (BABYLON) {
  78489. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  78490. __extends(AnaglyphFreeCamera, _super);
  78491. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  78492. var _this = _super.call(this, name, position, scene) || this;
  78493. _this.interaxialDistance = interaxialDistance;
  78494. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78495. return _this;
  78496. }
  78497. AnaglyphFreeCamera.prototype.getClassName = function () {
  78498. return "AnaglyphFreeCamera";
  78499. };
  78500. return AnaglyphFreeCamera;
  78501. }(BABYLON.FreeCamera));
  78502. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  78503. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  78504. __extends(AnaglyphArcRotateCamera, _super);
  78505. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  78506. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78507. _this.interaxialDistance = interaxialDistance;
  78508. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78509. return _this;
  78510. }
  78511. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  78512. return "AnaglyphArcRotateCamera";
  78513. };
  78514. return AnaglyphArcRotateCamera;
  78515. }(BABYLON.ArcRotateCamera));
  78516. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  78517. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  78518. __extends(AnaglyphGamepadCamera, _super);
  78519. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  78520. var _this = _super.call(this, name, position, scene) || this;
  78521. _this.interaxialDistance = interaxialDistance;
  78522. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78523. return _this;
  78524. }
  78525. AnaglyphGamepadCamera.prototype.getClassName = function () {
  78526. return "AnaglyphGamepadCamera";
  78527. };
  78528. return AnaglyphGamepadCamera;
  78529. }(BABYLON.GamepadCamera));
  78530. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  78531. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  78532. __extends(AnaglyphUniversalCamera, _super);
  78533. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  78534. var _this = _super.call(this, name, position, scene) || this;
  78535. _this.interaxialDistance = interaxialDistance;
  78536. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78537. return _this;
  78538. }
  78539. AnaglyphUniversalCamera.prototype.getClassName = function () {
  78540. return "AnaglyphUniversalCamera";
  78541. };
  78542. return AnaglyphUniversalCamera;
  78543. }(BABYLON.UniversalCamera));
  78544. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  78545. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  78546. __extends(StereoscopicFreeCamera, _super);
  78547. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78548. var _this = _super.call(this, name, position, scene) || this;
  78549. _this.interaxialDistance = interaxialDistance;
  78550. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78551. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78552. return _this;
  78553. }
  78554. StereoscopicFreeCamera.prototype.getClassName = function () {
  78555. return "StereoscopicFreeCamera";
  78556. };
  78557. return StereoscopicFreeCamera;
  78558. }(BABYLON.FreeCamera));
  78559. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  78560. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  78561. __extends(StereoscopicArcRotateCamera, _super);
  78562. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  78563. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78564. _this.interaxialDistance = interaxialDistance;
  78565. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78566. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78567. return _this;
  78568. }
  78569. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  78570. return "StereoscopicArcRotateCamera";
  78571. };
  78572. return StereoscopicArcRotateCamera;
  78573. }(BABYLON.ArcRotateCamera));
  78574. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  78575. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  78576. __extends(StereoscopicGamepadCamera, _super);
  78577. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78578. var _this = _super.call(this, name, position, scene) || this;
  78579. _this.interaxialDistance = interaxialDistance;
  78580. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78581. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78582. return _this;
  78583. }
  78584. StereoscopicGamepadCamera.prototype.getClassName = function () {
  78585. return "StereoscopicGamepadCamera";
  78586. };
  78587. return StereoscopicGamepadCamera;
  78588. }(BABYLON.GamepadCamera));
  78589. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  78590. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  78591. __extends(StereoscopicUniversalCamera, _super);
  78592. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78593. var _this = _super.call(this, name, position, scene) || this;
  78594. _this.interaxialDistance = interaxialDistance;
  78595. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78596. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78597. return _this;
  78598. }
  78599. StereoscopicUniversalCamera.prototype.getClassName = function () {
  78600. return "StereoscopicUniversalCamera";
  78601. };
  78602. return StereoscopicUniversalCamera;
  78603. }(BABYLON.UniversalCamera));
  78604. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  78605. })(BABYLON || (BABYLON = {}));
  78606. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  78607. var BABYLON;
  78608. (function (BABYLON) {
  78609. /**
  78610. * Helps to quickly add VR support to an existing scene.
  78611. * See http://doc.babylonjs.com/how_to/webvr_helper
  78612. */
  78613. var VRExperienceHelper = /** @class */ (function () {
  78614. /**
  78615. * Instantiates a VRExperienceHelper.
  78616. * Helps to quickly add VR support to an existing scene.
  78617. * @param scene The scene the VRExperienceHelper belongs to.
  78618. * @param webVROptions Options to modify the vr experience helper's behavior.
  78619. */
  78620. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  78621. if (webVROptions === void 0) { webVROptions = {}; }
  78622. var _this = this;
  78623. this.webVROptions = webVROptions;
  78624. // Can the system support WebVR, even if a headset isn't plugged in?
  78625. this._webVRsupported = false;
  78626. // If WebVR is supported, is a headset plugged in and are we ready to present?
  78627. this._webVRready = false;
  78628. // Are we waiting for the requestPresent callback to complete?
  78629. this._webVRrequesting = false;
  78630. // Are we presenting to the headset right now?
  78631. this._webVRpresenting = false;
  78632. // Are we presenting in the fullscreen fallback?
  78633. this._fullscreenVRpresenting = false;
  78634. /**
  78635. * Observable raised when entering VR.
  78636. */
  78637. this.onEnteringVRObservable = new BABYLON.Observable();
  78638. /**
  78639. * Observable raised when exiting VR.
  78640. */
  78641. this.onExitingVRObservable = new BABYLON.Observable();
  78642. /**
  78643. * Observable raised when controller mesh is loaded.
  78644. */
  78645. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78646. this._useCustomVRButton = false;
  78647. this._teleportationRequested = false;
  78648. this._teleportationEnabledOnLeftController = false;
  78649. this._teleportationEnabledOnRightController = false;
  78650. this._interactionsEnabledOnLeftController = false;
  78651. this._interactionsEnabledOnRightController = false;
  78652. this._leftControllerReady = false;
  78653. this._rightControllerReady = false;
  78654. this._floorMeshesCollection = [];
  78655. this._teleportationAllowed = false;
  78656. this._rotationAllowed = true;
  78657. this._teleportationRequestInitiated = false;
  78658. this._teleportationBackRequestInitiated = false;
  78659. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  78660. this._rotationRightAsked = false;
  78661. this._rotationLeftAsked = false;
  78662. this._isDefaultTeleportationTarget = true;
  78663. this._teleportationFillColor = "#444444";
  78664. this._teleportationBorderColor = "#FFFFFF";
  78665. this._rotationAngle = 0;
  78666. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  78667. this._padSensibilityUp = 0.65;
  78668. this._padSensibilityDown = 0.35;
  78669. /**
  78670. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  78671. */
  78672. this.onNewMeshSelected = new BABYLON.Observable();
  78673. /**
  78674. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  78675. */
  78676. this.onNewMeshPicked = new BABYLON.Observable();
  78677. /**
  78678. * Observable raised before camera teleportation
  78679. */
  78680. this.onBeforeCameraTeleport = new BABYLON.Observable();
  78681. /**
  78682. * Observable raised after camera teleportation
  78683. */
  78684. this.onAfterCameraTeleport = new BABYLON.Observable();
  78685. /**
  78686. * Observable raised when current selected mesh gets unselected
  78687. */
  78688. this.onSelectedMeshUnselected = new BABYLON.Observable();
  78689. /**
  78690. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  78691. */
  78692. this.teleportationEnabled = true;
  78693. this._pointerDownOnMeshAsked = false;
  78694. this._isActionableMesh = false;
  78695. this._teleportationInitialized = false;
  78696. this._interactionsEnabled = false;
  78697. this._interactionsRequested = false;
  78698. this._displayGaze = true;
  78699. this._displayLaserPointer = true;
  78700. this._dpadPressed = true;
  78701. this._onResize = function () {
  78702. _this.moveButtonToBottomRight();
  78703. if (_this._fullscreenVRpresenting && _this._webVRready) {
  78704. _this.exitVR();
  78705. }
  78706. };
  78707. this._onFullscreenChange = function () {
  78708. if (document.fullscreen !== undefined) {
  78709. _this._fullscreenVRpresenting = document.fullscreen;
  78710. }
  78711. else if (document.mozFullScreen !== undefined) {
  78712. _this._fullscreenVRpresenting = document.mozFullScreen;
  78713. }
  78714. else if (document.webkitIsFullScreen !== undefined) {
  78715. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  78716. }
  78717. else if (document.msIsFullScreen !== undefined) {
  78718. _this._fullscreenVRpresenting = document.msIsFullScreen;
  78719. }
  78720. if (!_this._fullscreenVRpresenting && _this._canvas) {
  78721. _this.exitVR();
  78722. if (!_this._useCustomVRButton) {
  78723. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  78724. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  78725. }
  78726. }
  78727. };
  78728. this.beforeRender = function () {
  78729. _this._castRayAndSelectObject();
  78730. };
  78731. this._onNewGamepadConnected = function (gamepad) {
  78732. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78733. if (gamepad.leftStick) {
  78734. gamepad.onleftstickchanged(function (stickValues) {
  78735. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  78736. // Listening to classic/xbox gamepad only if no VR controller is active
  78737. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  78738. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  78739. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  78740. _this._checkTeleportWithRay(stickValues);
  78741. _this._checkTeleportBackwards(stickValues);
  78742. }
  78743. }
  78744. });
  78745. }
  78746. if (gamepad.rightStick) {
  78747. gamepad.onrightstickchanged(function (stickValues) {
  78748. if (_this._teleportationInitialized) {
  78749. _this._checkRotate(stickValues);
  78750. }
  78751. });
  78752. }
  78753. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  78754. gamepad.onbuttondown(function (buttonPressed) {
  78755. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78756. _this._selectionPointerDown();
  78757. }
  78758. });
  78759. gamepad.onbuttonup(function (buttonPressed) {
  78760. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78761. _this._selectionPointerUp();
  78762. }
  78763. });
  78764. }
  78765. }
  78766. else {
  78767. var webVRController = gamepad;
  78768. _this._tryEnableInteractionOnController(webVRController);
  78769. }
  78770. };
  78771. // 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
  78772. this._tryEnableInteractionOnController = function (webVRController) {
  78773. if (webVRController.hand === "left") {
  78774. _this._leftControllerReady = true;
  78775. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  78776. _this._enableInteractionOnController(webVRController);
  78777. }
  78778. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  78779. _this._enableTeleportationOnController(webVRController);
  78780. }
  78781. }
  78782. if (webVRController.hand === "right") {
  78783. _this._rightControllerReady = true;
  78784. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  78785. _this._enableInteractionOnController(webVRController);
  78786. }
  78787. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  78788. _this._enableTeleportationOnController(webVRController);
  78789. }
  78790. }
  78791. };
  78792. this._onNewGamepadDisconnected = function (gamepad) {
  78793. if (gamepad instanceof BABYLON.WebVRController) {
  78794. if (gamepad.hand === "left") {
  78795. _this._interactionsEnabledOnLeftController = false;
  78796. _this._teleportationEnabledOnLeftController = false;
  78797. _this._leftControllerReady = false;
  78798. if (_this._leftLaserPointer) {
  78799. _this._leftLaserPointer.dispose();
  78800. }
  78801. }
  78802. if (gamepad.hand === "right") {
  78803. _this._interactionsEnabledOnRightController = false;
  78804. _this._teleportationEnabledOnRightController = false;
  78805. _this._rightControllerReady = false;
  78806. if (_this._rightLaserPointer) {
  78807. _this._rightLaserPointer.dispose();
  78808. }
  78809. }
  78810. }
  78811. };
  78812. this._workingVector = BABYLON.Vector3.Zero();
  78813. this._workingQuaternion = BABYLON.Quaternion.Identity();
  78814. this._workingMatrix = BABYLON.Matrix.Identity();
  78815. this._scene = scene;
  78816. this._canvas = scene.getEngine().getRenderingCanvas();
  78817. // Parse options
  78818. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  78819. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  78820. }
  78821. if (webVROptions.createDeviceOrientationCamera === undefined) {
  78822. webVROptions.createDeviceOrientationCamera = true;
  78823. }
  78824. if (webVROptions.defaultHeight === undefined) {
  78825. webVROptions.defaultHeight = 1.7;
  78826. }
  78827. if (webVROptions.useCustomVRButton) {
  78828. this._useCustomVRButton = true;
  78829. if (webVROptions.customVRButton) {
  78830. this._btnVR = webVROptions.customVRButton;
  78831. }
  78832. }
  78833. if (webVROptions.rayLength) {
  78834. this._rayLength = webVROptions.rayLength;
  78835. }
  78836. this._defaultHeight = webVROptions.defaultHeight;
  78837. // Set position
  78838. if (this._scene.activeCamera) {
  78839. this._position = this._scene.activeCamera.position.clone();
  78840. }
  78841. else {
  78842. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  78843. }
  78844. // Set non-vr camera
  78845. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  78846. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  78847. // Copy data from existing camera
  78848. if (this._scene.activeCamera) {
  78849. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  78850. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  78851. // Set rotation from previous camera
  78852. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  78853. var targetCamera = this._scene.activeCamera;
  78854. if (targetCamera.rotationQuaternion) {
  78855. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  78856. }
  78857. else {
  78858. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  78859. }
  78860. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  78861. }
  78862. }
  78863. this._scene.activeCamera = this._deviceOrientationCamera;
  78864. if (this._canvas) {
  78865. this._scene.activeCamera.attachControl(this._canvas);
  78866. }
  78867. }
  78868. else {
  78869. this._existingCamera = this._scene.activeCamera;
  78870. }
  78871. // Create VR cameras
  78872. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78873. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  78874. }
  78875. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  78876. this._webVRCamera.useStandingMatrix();
  78877. // Create default button
  78878. if (!this._useCustomVRButton) {
  78879. this._btnVR = document.createElement("BUTTON");
  78880. this._btnVR.className = "babylonVRicon";
  78881. this._btnVR.id = "babylonVRiconbtn";
  78882. this._btnVR.title = "Click to switch to VR";
  78883. 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) }";
  78884. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  78885. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  78886. // css += ".babylonVRicon.vrdisplaysupported { }";
  78887. // css += ".babylonVRicon.vrdisplayready { }";
  78888. // css += ".babylonVRicon.vrdisplayrequesting { }";
  78889. var style = document.createElement('style');
  78890. style.appendChild(document.createTextNode(css));
  78891. document.getElementsByTagName('head')[0].appendChild(style);
  78892. this.moveButtonToBottomRight();
  78893. }
  78894. // VR button click event
  78895. if (this._btnVR) {
  78896. this._btnVR.addEventListener("click", function () {
  78897. if (!_this.isInVRMode) {
  78898. _this.enterVR();
  78899. }
  78900. else {
  78901. _this.exitVR();
  78902. }
  78903. });
  78904. }
  78905. // Window events
  78906. window.addEventListener("resize", this._onResize);
  78907. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  78908. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  78909. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  78910. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  78911. // Display vr button when headset is connected
  78912. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78913. this.displayVRButton();
  78914. }
  78915. else {
  78916. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  78917. if (e.vrDisplay) {
  78918. _this.displayVRButton();
  78919. }
  78920. });
  78921. }
  78922. // Exiting VR mode using 'ESC' key on desktop
  78923. this._onKeyDown = function (event) {
  78924. if (event.keyCode === 27 && _this.isInVRMode) {
  78925. _this.exitVR();
  78926. }
  78927. };
  78928. document.addEventListener("keydown", this._onKeyDown);
  78929. // Exiting VR mode double tapping the touch screen
  78930. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  78931. if (_this.isInVRMode) {
  78932. _this.exitVR();
  78933. if (_this._fullscreenVRpresenting) {
  78934. _this._scene.getEngine().switchFullscreen(true);
  78935. }
  78936. }
  78937. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  78938. // Listen for WebVR display changes
  78939. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  78940. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  78941. this._onVRRequestPresentStart = function () {
  78942. _this._webVRrequesting = true;
  78943. _this.updateButtonVisibility();
  78944. };
  78945. this._onVRRequestPresentComplete = function (success) {
  78946. _this._webVRrequesting = false;
  78947. _this.updateButtonVisibility();
  78948. };
  78949. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  78950. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  78951. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  78952. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  78953. scene.onDisposeObservable.add(function () {
  78954. _this.dispose();
  78955. });
  78956. // Gamepad connection events
  78957. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  78958. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  78959. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  78960. this.updateButtonVisibility();
  78961. //create easing functions
  78962. this._circleEase = new BABYLON.CircleEase();
  78963. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  78964. }
  78965. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  78966. /** Return this.onEnteringVRObservable
  78967. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  78968. */
  78969. get: function () {
  78970. return this.onEnteringVRObservable;
  78971. },
  78972. enumerable: true,
  78973. configurable: true
  78974. });
  78975. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  78976. /** Return this.onExitingVRObservable
  78977. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  78978. */
  78979. get: function () {
  78980. return this.onExitingVRObservable;
  78981. },
  78982. enumerable: true,
  78983. configurable: true
  78984. });
  78985. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  78986. /** Return this.onControllerMeshLoadedObservable
  78987. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  78988. */
  78989. get: function () {
  78990. return this.onControllerMeshLoadedObservable;
  78991. },
  78992. enumerable: true,
  78993. configurable: true
  78994. });
  78995. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  78996. /**
  78997. * The mesh used to display where the user is going to teleport.
  78998. */
  78999. get: function () {
  79000. return this._teleportationTarget;
  79001. },
  79002. /**
  79003. * Sets the mesh to be used to display where the user is going to teleport.
  79004. */
  79005. set: function (value) {
  79006. if (value) {
  79007. value.name = "teleportationTarget";
  79008. this._isDefaultTeleportationTarget = false;
  79009. this._teleportationTarget = value;
  79010. }
  79011. },
  79012. enumerable: true,
  79013. configurable: true
  79014. });
  79015. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  79016. /**
  79017. * The mesh used to display where the user is selecting.
  79018. */
  79019. get: function () {
  79020. return this._gazeTracker;
  79021. },
  79022. /**
  79023. * Sets the mesh to be used to display where the user is selecting.
  79024. */
  79025. set: function (value) {
  79026. if (value) {
  79027. this._gazeTracker = value;
  79028. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79029. this._gazeTracker.isPickable = false;
  79030. this._gazeTracker.isVisible = false;
  79031. }
  79032. },
  79033. enumerable: true,
  79034. configurable: true
  79035. });
  79036. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  79037. /**
  79038. * If the ray of the gaze should be displayed.
  79039. */
  79040. get: function () {
  79041. return this._displayGaze;
  79042. },
  79043. /**
  79044. * Sets if the ray of the gaze should be displayed.
  79045. */
  79046. set: function (value) {
  79047. this._displayGaze = value;
  79048. if (!value) {
  79049. this._gazeTracker.isVisible = false;
  79050. }
  79051. },
  79052. enumerable: true,
  79053. configurable: true
  79054. });
  79055. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  79056. /**
  79057. * If the ray of the LaserPointer should be displayed.
  79058. */
  79059. get: function () {
  79060. return this._displayLaserPointer;
  79061. },
  79062. /**
  79063. * Sets if the ray of the LaserPointer should be displayed.
  79064. */
  79065. set: function (value) {
  79066. this._displayLaserPointer = value;
  79067. if (!value) {
  79068. if (this._rightLaserPointer) {
  79069. this._rightLaserPointer.isVisible = false;
  79070. }
  79071. if (this._leftLaserPointer) {
  79072. this._leftLaserPointer.isVisible = false;
  79073. }
  79074. }
  79075. else {
  79076. if (this._rightLaserPointer) {
  79077. this._rightLaserPointer.isVisible = true;
  79078. }
  79079. else if (this._leftLaserPointer) {
  79080. this._leftLaserPointer.isVisible = true;
  79081. }
  79082. }
  79083. },
  79084. enumerable: true,
  79085. configurable: true
  79086. });
  79087. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  79088. /**
  79089. * The deviceOrientationCamera used as the camera when not in VR.
  79090. */
  79091. get: function () {
  79092. return this._deviceOrientationCamera;
  79093. },
  79094. enumerable: true,
  79095. configurable: true
  79096. });
  79097. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  79098. /**
  79099. * Based on the current WebVR support, returns the current VR camera used.
  79100. */
  79101. get: function () {
  79102. if (this._webVRready) {
  79103. return this._webVRCamera;
  79104. }
  79105. else {
  79106. return this._scene.activeCamera;
  79107. }
  79108. },
  79109. enumerable: true,
  79110. configurable: true
  79111. });
  79112. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  79113. /**
  79114. * The webVRCamera which is used when in VR.
  79115. */
  79116. get: function () {
  79117. return this._webVRCamera;
  79118. },
  79119. enumerable: true,
  79120. configurable: true
  79121. });
  79122. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  79123. /**
  79124. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  79125. */
  79126. get: function () {
  79127. return this._vrDeviceOrientationCamera;
  79128. },
  79129. enumerable: true,
  79130. configurable: true
  79131. });
  79132. // Raised when one of the controller has loaded successfully its associated default mesh
  79133. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  79134. this._tryEnableInteractionOnController(webVRController);
  79135. try {
  79136. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  79137. }
  79138. catch (err) {
  79139. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  79140. }
  79141. };
  79142. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  79143. /**
  79144. * Gets a value indicating if we are currently in VR mode.
  79145. */
  79146. get: function () {
  79147. return this._webVRpresenting || this._fullscreenVRpresenting;
  79148. },
  79149. enumerable: true,
  79150. configurable: true
  79151. });
  79152. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  79153. var vrDisplay = this._scene.getEngine().getVRDevice();
  79154. if (vrDisplay) {
  79155. var wasPresenting = this._webVRpresenting;
  79156. // A VR display is connected
  79157. this._webVRpresenting = vrDisplay.isPresenting;
  79158. if (wasPresenting && !this._webVRpresenting)
  79159. this.exitVR();
  79160. }
  79161. else {
  79162. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  79163. }
  79164. this.updateButtonVisibility();
  79165. };
  79166. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  79167. this._webVRsupported = eventArgs.vrSupported;
  79168. this._webVRready = !!eventArgs.vrDisplay;
  79169. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  79170. this.updateButtonVisibility();
  79171. };
  79172. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  79173. if (this._canvas && !this._useCustomVRButton) {
  79174. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  79175. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  79176. }
  79177. };
  79178. VRExperienceHelper.prototype.displayVRButton = function () {
  79179. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  79180. document.body.appendChild(this._btnVR);
  79181. this._btnVRDisplayed = true;
  79182. }
  79183. };
  79184. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  79185. if (!this._btnVR || this._useCustomVRButton) {
  79186. return;
  79187. }
  79188. this._btnVR.className = "babylonVRicon";
  79189. if (this.isInVRMode) {
  79190. this._btnVR.className += " vrdisplaypresenting";
  79191. }
  79192. else {
  79193. if (this._webVRready)
  79194. this._btnVR.className += " vrdisplayready";
  79195. if (this._webVRsupported)
  79196. this._btnVR.className += " vrdisplaysupported";
  79197. if (this._webVRrequesting)
  79198. this._btnVR.className += " vrdisplayrequesting";
  79199. }
  79200. };
  79201. /**
  79202. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  79203. * Otherwise, will use the fullscreen API.
  79204. */
  79205. VRExperienceHelper.prototype.enterVR = function () {
  79206. if (this.onEnteringVRObservable) {
  79207. try {
  79208. this.onEnteringVRObservable.notifyObservers(this);
  79209. }
  79210. catch (err) {
  79211. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  79212. }
  79213. }
  79214. if (this._scene.activeCamera) {
  79215. this._position = this._scene.activeCamera.position.clone();
  79216. // make sure that we return to the last active camera
  79217. this._existingCamera = this._scene.activeCamera;
  79218. }
  79219. if (this._webVRrequesting)
  79220. return;
  79221. // If WebVR is supported and a headset is connected
  79222. if (this._webVRready) {
  79223. if (!this._webVRpresenting) {
  79224. this._webVRCamera.position = this._position;
  79225. this._scene.activeCamera = this._webVRCamera;
  79226. }
  79227. }
  79228. else if (this._vrDeviceOrientationCamera) {
  79229. this._vrDeviceOrientationCamera.position = this._position;
  79230. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  79231. this._scene.getEngine().switchFullscreen(true);
  79232. this.updateButtonVisibility();
  79233. }
  79234. if (this._scene.activeCamera && this._canvas) {
  79235. this._scene.activeCamera.attachControl(this._canvas);
  79236. }
  79237. if (this._interactionsEnabled) {
  79238. this._scene.registerBeforeRender(this.beforeRender);
  79239. }
  79240. };
  79241. /**
  79242. * Attempt to exit VR, or fullscreen.
  79243. */
  79244. VRExperienceHelper.prototype.exitVR = function () {
  79245. if (this.onExitingVRObservable) {
  79246. try {
  79247. this.onExitingVRObservable.notifyObservers(this);
  79248. }
  79249. catch (err) {
  79250. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  79251. }
  79252. }
  79253. if (this._webVRpresenting) {
  79254. this._scene.getEngine().disableVR();
  79255. }
  79256. if (this._scene.activeCamera) {
  79257. this._position = this._scene.activeCamera.position.clone();
  79258. }
  79259. if (this._deviceOrientationCamera) {
  79260. this._deviceOrientationCamera.position = this._position;
  79261. this._scene.activeCamera = this._deviceOrientationCamera;
  79262. if (this._canvas) {
  79263. this._scene.activeCamera.attachControl(this._canvas);
  79264. }
  79265. }
  79266. else if (this._existingCamera) {
  79267. this._existingCamera.position = this._position;
  79268. this._scene.activeCamera = this._existingCamera;
  79269. }
  79270. this.updateButtonVisibility();
  79271. if (this._interactionsEnabled) {
  79272. this._scene.unregisterBeforeRender(this.beforeRender);
  79273. }
  79274. };
  79275. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  79276. /**
  79277. * The position of the vr experience helper.
  79278. */
  79279. get: function () {
  79280. return this._position;
  79281. },
  79282. /**
  79283. * Sets the position of the vr experience helper.
  79284. */
  79285. set: function (value) {
  79286. this._position = value;
  79287. if (this._scene.activeCamera) {
  79288. this._scene.activeCamera.position = value;
  79289. }
  79290. },
  79291. enumerable: true,
  79292. configurable: true
  79293. });
  79294. /**
  79295. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  79296. */
  79297. VRExperienceHelper.prototype.enableInteractions = function () {
  79298. var _this = this;
  79299. if (!this._interactionsEnabled) {
  79300. this._interactionsRequested = true;
  79301. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79302. this._enableInteractionOnController(this._webVRCamera.leftController);
  79303. }
  79304. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79305. this._enableInteractionOnController(this._webVRCamera.rightController);
  79306. }
  79307. if (!this._gazeTracker) {
  79308. this._createGazeTracker();
  79309. }
  79310. this.raySelectionPredicate = function (mesh) {
  79311. return mesh.isVisible;
  79312. };
  79313. this.meshSelectionPredicate = function (mesh) {
  79314. return true;
  79315. };
  79316. this._raySelectionPredicate = function (mesh) {
  79317. if (_this._isTeleportationFloor(mesh) || (mesh != _this._gazeTracker
  79318. && mesh.name.indexOf("teleportationTarget") === -1
  79319. && mesh.name.indexOf("torusTeleportation") === -1
  79320. && mesh.name.indexOf("laserPointer") === -1)) {
  79321. return _this.raySelectionPredicate(mesh);
  79322. }
  79323. return false;
  79324. };
  79325. this._interactionsEnabled = true;
  79326. }
  79327. };
  79328. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  79329. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  79330. if (this._floorMeshesCollection[i].id === mesh.id) {
  79331. return true;
  79332. }
  79333. }
  79334. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  79335. return true;
  79336. }
  79337. return false;
  79338. };
  79339. /**
  79340. * Adds a floor mesh to be used for teleportation.
  79341. * @param floorMesh the mesh to be used for teleportation.
  79342. */
  79343. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  79344. if (!this._floorMeshesCollection) {
  79345. return;
  79346. }
  79347. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  79348. return;
  79349. }
  79350. this._floorMeshesCollection.push(floorMesh);
  79351. };
  79352. /**
  79353. * Removes a floor mesh from being used for teleportation.
  79354. * @param floorMesh the mesh to be removed.
  79355. */
  79356. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  79357. if (!this._floorMeshesCollection) {
  79358. return;
  79359. }
  79360. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  79361. if (meshIndex !== -1) {
  79362. this._floorMeshesCollection.splice(meshIndex, 1);
  79363. }
  79364. };
  79365. /**
  79366. * Enables interactions and teleportation using the VR controllers and gaze.
  79367. * @param vrTeleportationOptions options to modify teleportation behavior.
  79368. */
  79369. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  79370. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  79371. if (!this._teleportationInitialized) {
  79372. this._teleportationRequested = true;
  79373. this.enableInteractions();
  79374. if (vrTeleportationOptions.floorMeshName) {
  79375. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  79376. }
  79377. if (vrTeleportationOptions.floorMeshes) {
  79378. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  79379. }
  79380. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79381. this._enableTeleportationOnController(this._webVRCamera.leftController);
  79382. }
  79383. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79384. this._enableTeleportationOnController(this._webVRCamera.rightController);
  79385. }
  79386. // Creates an image processing post process for the vignette not relying
  79387. // on the main scene configuration for image processing to reduce setup and spaces
  79388. // (gamma/linear) conflicts.
  79389. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  79390. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  79391. imageProcessingConfiguration.vignetteEnabled = true;
  79392. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  79393. this._webVRCamera.detachPostProcess(this._postProcessMove);
  79394. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  79395. this._teleportationInitialized = true;
  79396. if (this._isDefaultTeleportationTarget) {
  79397. this._createTeleportationCircles();
  79398. }
  79399. }
  79400. };
  79401. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  79402. var _this = this;
  79403. var controllerMesh = webVRController.mesh;
  79404. if (controllerMesh) {
  79405. var makeNotPick = function (root) {
  79406. root.name += " laserPointer";
  79407. root.getChildMeshes().forEach(function (c) {
  79408. makeNotPick(c);
  79409. });
  79410. };
  79411. makeNotPick(controllerMesh);
  79412. var childMeshes = controllerMesh.getChildMeshes();
  79413. for (var i = 0; i < childMeshes.length; i++) {
  79414. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  79415. controllerMesh = childMeshes[i];
  79416. break;
  79417. }
  79418. }
  79419. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  79420. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  79421. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79422. laserPointerMaterial.alpha = 0.6;
  79423. laserPointer.material = laserPointerMaterial;
  79424. laserPointer.rotation.x = Math.PI / 2;
  79425. laserPointer.parent = controllerMesh;
  79426. laserPointer.position.z = -0.5;
  79427. laserPointer.isVisible = false;
  79428. if (webVRController.hand === "left") {
  79429. this._leftLaserPointer = laserPointer;
  79430. this._interactionsEnabledOnLeftController = true;
  79431. if (!this._rightLaserPointer) {
  79432. this._leftLaserPointer.isVisible = true;
  79433. }
  79434. }
  79435. else {
  79436. this._rightLaserPointer = laserPointer;
  79437. this._interactionsEnabledOnRightController = true;
  79438. if (!this._leftLaserPointer) {
  79439. this._rightLaserPointer.isVisible = true;
  79440. }
  79441. }
  79442. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  79443. // Enabling / disabling laserPointer
  79444. if (_this._displayLaserPointer && stateObject.value === 1) {
  79445. laserPointer.isVisible = !laserPointer.isVisible;
  79446. // Laser pointer can only be active on left or right, not both at the same time
  79447. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  79448. _this._rightLaserPointer.isVisible = false;
  79449. }
  79450. else if (_this._leftLaserPointer) {
  79451. _this._leftLaserPointer.isVisible = false;
  79452. }
  79453. }
  79454. });
  79455. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  79456. if (!_this._pointerDownOnMeshAsked) {
  79457. if (stateObject.value > _this._padSensibilityUp) {
  79458. _this._selectionPointerDown();
  79459. }
  79460. }
  79461. else if (stateObject.value < _this._padSensibilityDown) {
  79462. _this._selectionPointerUp();
  79463. }
  79464. });
  79465. }
  79466. };
  79467. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  79468. if (webVRController === void 0) { webVRController = null; }
  79469. if (!this._teleportationRequestInitiated) {
  79470. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  79471. if (webVRController) {
  79472. // If laser pointer wasn't enabled yet
  79473. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  79474. this._leftLaserPointer.isVisible = true;
  79475. if (this._rightLaserPointer) {
  79476. this._rightLaserPointer.isVisible = false;
  79477. }
  79478. }
  79479. else if (this._displayLaserPointer && this._rightLaserPointer) {
  79480. this._rightLaserPointer.isVisible = true;
  79481. if (this._leftLaserPointer) {
  79482. this._leftLaserPointer.isVisible = false;
  79483. }
  79484. }
  79485. }
  79486. this._teleportationRequestInitiated = true;
  79487. }
  79488. }
  79489. else {
  79490. // Listening to the proper controller values changes to confirm teleportation
  79491. if (webVRController == null
  79492. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  79493. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  79494. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  79495. if (this._teleportationAllowed) {
  79496. this._teleportationAllowed = false;
  79497. this._teleportCamera();
  79498. }
  79499. this._teleportationRequestInitiated = false;
  79500. }
  79501. }
  79502. }
  79503. };
  79504. VRExperienceHelper.prototype._selectionPointerDown = function () {
  79505. this._pointerDownOnMeshAsked = true;
  79506. if (this._currentMeshSelected && this._currentHit) {
  79507. this._scene.simulatePointerDown(this._currentHit);
  79508. }
  79509. };
  79510. VRExperienceHelper.prototype._selectionPointerUp = function () {
  79511. if (this._currentMeshSelected && this._currentHit) {
  79512. this._scene.simulatePointerUp(this._currentHit);
  79513. }
  79514. this._pointerDownOnMeshAsked = false;
  79515. };
  79516. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  79517. // Only rotate when user is not currently selecting a teleportation location
  79518. if (this._teleportationRequestInitiated) {
  79519. return;
  79520. }
  79521. if (!this._rotationLeftAsked) {
  79522. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  79523. this._rotationLeftAsked = true;
  79524. if (this._rotationAllowed) {
  79525. this._rotateCamera(false);
  79526. }
  79527. }
  79528. }
  79529. else {
  79530. if (stateObject.x > -this._padSensibilityDown) {
  79531. this._rotationLeftAsked = false;
  79532. }
  79533. }
  79534. if (!this._rotationRightAsked) {
  79535. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  79536. this._rotationRightAsked = true;
  79537. if (this._rotationAllowed) {
  79538. this._rotateCamera(true);
  79539. }
  79540. }
  79541. }
  79542. else {
  79543. if (stateObject.x < this._padSensibilityDown) {
  79544. this._rotationRightAsked = false;
  79545. }
  79546. }
  79547. };
  79548. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  79549. // Only teleport backwards when user is not currently selecting a teleportation location
  79550. if (this._teleportationRequestInitiated) {
  79551. return;
  79552. }
  79553. // Teleport backwards
  79554. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  79555. if (!this._teleportationBackRequestInitiated) {
  79556. if (!this.currentVRCamera) {
  79557. return;
  79558. }
  79559. // Get rotation and position of the current camera
  79560. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  79561. var position = this.currentVRCamera.position;
  79562. // If the camera has device position, use that instead
  79563. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  79564. rotation = this.currentVRCamera.deviceRotationQuaternion;
  79565. position = this.currentVRCamera.devicePosition;
  79566. }
  79567. // Get matrix with only the y rotation of the device rotation
  79568. rotation.toEulerAnglesToRef(this._workingVector);
  79569. this._workingVector.z = 0;
  79570. this._workingVector.x = 0;
  79571. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  79572. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  79573. // Rotate backwards ray by device rotation to cast at the ground behind the user
  79574. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  79575. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  79576. var ray = new BABYLON.Ray(position, this._workingVector);
  79577. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79578. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  79579. this._teleportCamera(hit.pickedPoint);
  79580. }
  79581. this._teleportationBackRequestInitiated = true;
  79582. }
  79583. }
  79584. else {
  79585. this._teleportationBackRequestInitiated = false;
  79586. }
  79587. };
  79588. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  79589. var _this = this;
  79590. var controllerMesh = webVRController.mesh;
  79591. if (controllerMesh) {
  79592. if (webVRController.hand === "left") {
  79593. if (!this._interactionsEnabledOnLeftController) {
  79594. this._enableInteractionOnController(webVRController);
  79595. }
  79596. this._teleportationEnabledOnLeftController = true;
  79597. }
  79598. else {
  79599. if (!this._interactionsEnabledOnRightController) {
  79600. this._enableInteractionOnController(webVRController);
  79601. }
  79602. this._teleportationEnabledOnRightController = true;
  79603. }
  79604. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79605. this._dpadPressed = false;
  79606. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  79607. _this._dpadPressed = stateObject.pressed;
  79608. if (!_this._dpadPressed) {
  79609. _this._rotationLeftAsked = false;
  79610. _this._rotationRightAsked = false;
  79611. _this._teleportationBackRequestInitiated = false;
  79612. }
  79613. });
  79614. }
  79615. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  79616. if (_this.teleportationEnabled) {
  79617. _this._checkTeleportBackwards(stateObject);
  79618. _this._checkTeleportWithRay(stateObject, webVRController);
  79619. }
  79620. _this._checkRotate(stateObject);
  79621. });
  79622. }
  79623. };
  79624. // Gaze support used to point to teleport or to interact with an object
  79625. VRExperienceHelper.prototype._createGazeTracker = function () {
  79626. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  79627. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79628. this._gazeTracker.isPickable = false;
  79629. this._gazeTracker.isVisible = false;
  79630. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  79631. targetMat.specularColor = BABYLON.Color3.Black();
  79632. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79633. targetMat.backFaceCulling = false;
  79634. this._gazeTracker.material = targetMat;
  79635. };
  79636. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  79637. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  79638. this._teleportationTarget.isPickable = false;
  79639. var length = 512;
  79640. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  79641. dynamicTexture.hasAlpha = true;
  79642. var context = dynamicTexture.getContext();
  79643. var centerX = length / 2;
  79644. var centerY = length / 2;
  79645. var radius = 200;
  79646. context.beginPath();
  79647. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  79648. context.fillStyle = this._teleportationFillColor;
  79649. context.fill();
  79650. context.lineWidth = 10;
  79651. context.strokeStyle = this._teleportationBorderColor;
  79652. context.stroke();
  79653. context.closePath();
  79654. dynamicTexture.update();
  79655. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  79656. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  79657. this._teleportationTarget.material = teleportationCircleMaterial;
  79658. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  79659. torus.isPickable = false;
  79660. torus.parent = this._teleportationTarget;
  79661. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  79662. var keys = [];
  79663. keys.push({
  79664. frame: 0,
  79665. value: 0
  79666. });
  79667. keys.push({
  79668. frame: 30,
  79669. value: 0.4
  79670. });
  79671. keys.push({
  79672. frame: 60,
  79673. value: 0
  79674. });
  79675. animationInnerCircle.setKeys(keys);
  79676. var easingFunction = new BABYLON.SineEase();
  79677. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79678. animationInnerCircle.setEasingFunction(easingFunction);
  79679. torus.animations = [];
  79680. torus.animations.push(animationInnerCircle);
  79681. this._scene.beginAnimation(torus, 0, 60, true);
  79682. this._hideTeleportationTarget();
  79683. };
  79684. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  79685. if (this._teleportationInitialized) {
  79686. this._teleportationTarget.isVisible = true;
  79687. if (this._isDefaultTeleportationTarget) {
  79688. this._teleportationTarget.getChildren()[0].isVisible = true;
  79689. }
  79690. }
  79691. };
  79692. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  79693. if (this._teleportationInitialized) {
  79694. this._teleportationTarget.isVisible = false;
  79695. if (this._isDefaultTeleportationTarget) {
  79696. this._teleportationTarget.getChildren()[0].isVisible = false;
  79697. }
  79698. }
  79699. };
  79700. VRExperienceHelper.prototype._rotateCamera = function (right) {
  79701. var _this = this;
  79702. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79703. return;
  79704. }
  79705. if (right) {
  79706. this._rotationAngle++;
  79707. }
  79708. else {
  79709. this._rotationAngle--;
  79710. }
  79711. this.currentVRCamera.animations = [];
  79712. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  79713. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79714. var animationRotationKeys = [];
  79715. animationRotationKeys.push({
  79716. frame: 0,
  79717. value: this.currentVRCamera.rotationQuaternion
  79718. });
  79719. animationRotationKeys.push({
  79720. frame: 6,
  79721. value: target
  79722. });
  79723. animationRotation.setKeys(animationRotationKeys);
  79724. animationRotation.setEasingFunction(this._circleEase);
  79725. this.currentVRCamera.animations.push(animationRotation);
  79726. this._postProcessMove.animations = [];
  79727. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79728. var vignetteWeightKeys = [];
  79729. vignetteWeightKeys.push({
  79730. frame: 0,
  79731. value: 0
  79732. });
  79733. vignetteWeightKeys.push({
  79734. frame: 3,
  79735. value: 4
  79736. });
  79737. vignetteWeightKeys.push({
  79738. frame: 6,
  79739. value: 0
  79740. });
  79741. animationPP.setKeys(vignetteWeightKeys);
  79742. animationPP.setEasingFunction(this._circleEase);
  79743. this._postProcessMove.animations.push(animationPP);
  79744. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79745. var vignetteStretchKeys = [];
  79746. vignetteStretchKeys.push({
  79747. frame: 0,
  79748. value: 0
  79749. });
  79750. vignetteStretchKeys.push({
  79751. frame: 3,
  79752. value: 10
  79753. });
  79754. vignetteStretchKeys.push({
  79755. frame: 6,
  79756. value: 0
  79757. });
  79758. animationPP2.setKeys(vignetteStretchKeys);
  79759. animationPP2.setEasingFunction(this._circleEase);
  79760. this._postProcessMove.animations.push(animationPP2);
  79761. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79762. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79763. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79764. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  79765. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79766. });
  79767. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  79768. };
  79769. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  79770. if (hit.pickedPoint) {
  79771. this._teleportationAllowed = true;
  79772. if (this._teleportationRequestInitiated) {
  79773. this._displayTeleportationTarget();
  79774. }
  79775. else {
  79776. this._hideTeleportationTarget();
  79777. }
  79778. this._haloCenter.copyFrom(hit.pickedPoint);
  79779. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  79780. var pickNormal = hit.getNormal(true, false);
  79781. if (pickNormal) {
  79782. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79783. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79784. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  79785. }
  79786. this._teleportationTarget.position.y += 0.1;
  79787. }
  79788. };
  79789. VRExperienceHelper.prototype._teleportCamera = function (location) {
  79790. var _this = this;
  79791. if (location === void 0) { location = null; }
  79792. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79793. return;
  79794. }
  79795. if (!location) {
  79796. location = this._haloCenter;
  79797. }
  79798. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  79799. // offset of the headset from the anchor.
  79800. if (this.webVRCamera.leftCamera) {
  79801. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  79802. this._workingVector.subtractInPlace(this.webVRCamera.position);
  79803. location.subtractToRef(this._workingVector, this._workingVector);
  79804. }
  79805. else {
  79806. this._workingVector.copyFrom(location);
  79807. }
  79808. // Add height to account for user's height offset
  79809. if (this.isInVRMode) {
  79810. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  79811. }
  79812. else {
  79813. this._workingVector.y += this._defaultHeight;
  79814. }
  79815. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  79816. // Create animation from the camera's position to the new location
  79817. this.currentVRCamera.animations = [];
  79818. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79819. var animationCameraTeleportationKeys = [{
  79820. frame: 0,
  79821. value: this.currentVRCamera.position
  79822. },
  79823. {
  79824. frame: 11,
  79825. value: this._workingVector
  79826. }
  79827. ];
  79828. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  79829. animationCameraTeleportation.setEasingFunction(this._circleEase);
  79830. this.currentVRCamera.animations.push(animationCameraTeleportation);
  79831. this._postProcessMove.animations = [];
  79832. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79833. var vignetteWeightKeys = [];
  79834. vignetteWeightKeys.push({
  79835. frame: 0,
  79836. value: 0
  79837. });
  79838. vignetteWeightKeys.push({
  79839. frame: 5,
  79840. value: 8
  79841. });
  79842. vignetteWeightKeys.push({
  79843. frame: 11,
  79844. value: 0
  79845. });
  79846. animationPP.setKeys(vignetteWeightKeys);
  79847. this._postProcessMove.animations.push(animationPP);
  79848. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79849. var vignetteStretchKeys = [];
  79850. vignetteStretchKeys.push({
  79851. frame: 0,
  79852. value: 0
  79853. });
  79854. vignetteStretchKeys.push({
  79855. frame: 5,
  79856. value: 10
  79857. });
  79858. vignetteStretchKeys.push({
  79859. frame: 11,
  79860. value: 0
  79861. });
  79862. animationPP2.setKeys(vignetteStretchKeys);
  79863. this._postProcessMove.animations.push(animationPP2);
  79864. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79865. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79866. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79867. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  79868. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79869. });
  79870. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  79871. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  79872. });
  79873. };
  79874. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  79875. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79876. return;
  79877. }
  79878. var ray;
  79879. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  79880. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  79881. }
  79882. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  79883. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  79884. }
  79885. else {
  79886. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  79887. }
  79888. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79889. // Moving the gazeTracker on the mesh face targetted
  79890. if (hit && hit.pickedPoint) {
  79891. if (this._displayGaze) {
  79892. var multiplier = 1;
  79893. this._gazeTracker.isVisible = true;
  79894. if (this._isActionableMesh) {
  79895. multiplier = 3;
  79896. }
  79897. this._gazeTracker.scaling.x = hit.distance * multiplier;
  79898. this._gazeTracker.scaling.y = hit.distance * multiplier;
  79899. this._gazeTracker.scaling.z = hit.distance * multiplier;
  79900. var pickNormal = hit.getNormal();
  79901. // To avoid z-fighting
  79902. var deltaFighting = 0.002;
  79903. if (pickNormal) {
  79904. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79905. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79906. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  79907. }
  79908. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  79909. if (this._gazeTracker.position.x < 0) {
  79910. this._gazeTracker.position.x += deltaFighting;
  79911. }
  79912. else {
  79913. this._gazeTracker.position.x -= deltaFighting;
  79914. }
  79915. if (this._gazeTracker.position.y < 0) {
  79916. this._gazeTracker.position.y += deltaFighting;
  79917. }
  79918. else {
  79919. this._gazeTracker.position.y -= deltaFighting;
  79920. }
  79921. if (this._gazeTracker.position.z < 0) {
  79922. this._gazeTracker.position.z += deltaFighting;
  79923. }
  79924. else {
  79925. this._gazeTracker.position.z -= deltaFighting;
  79926. }
  79927. }
  79928. // Changing the size of the laser pointer based on the distance from the targetted point
  79929. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  79930. this._rightLaserPointer.scaling.y = hit.distance;
  79931. this._rightLaserPointer.position.z = -hit.distance / 2;
  79932. }
  79933. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  79934. this._leftLaserPointer.scaling.y = hit.distance;
  79935. this._leftLaserPointer.position.z = -hit.distance / 2;
  79936. }
  79937. }
  79938. else {
  79939. this._gazeTracker.isVisible = false;
  79940. }
  79941. if (hit && hit.pickedMesh) {
  79942. this._currentHit = hit;
  79943. if (this._pointerDownOnMeshAsked) {
  79944. this._scene.simulatePointerMove(this._currentHit);
  79945. }
  79946. // The object selected is the floor, we're in a teleportation scenario
  79947. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  79948. // Moving the teleportation area to this targetted point
  79949. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  79950. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  79951. this._notifySelectedMeshUnselected();
  79952. }
  79953. this._currentMeshSelected = null;
  79954. this._moveTeleportationSelectorTo(hit);
  79955. return;
  79956. }
  79957. // If not, we're in a selection scenario
  79958. this._hideTeleportationTarget();
  79959. this._teleportationAllowed = false;
  79960. if (hit.pickedMesh !== this._currentMeshSelected) {
  79961. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  79962. this.onNewMeshPicked.notifyObservers(hit);
  79963. this._currentMeshSelected = hit.pickedMesh;
  79964. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  79965. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  79966. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  79967. this._isActionableMesh = true;
  79968. }
  79969. else {
  79970. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79971. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79972. this._isActionableMesh = false;
  79973. }
  79974. try {
  79975. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  79976. }
  79977. catch (err) {
  79978. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  79979. }
  79980. }
  79981. else {
  79982. this._notifySelectedMeshUnselected();
  79983. this._currentMeshSelected = null;
  79984. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79985. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79986. }
  79987. }
  79988. }
  79989. else {
  79990. this._currentHit = null;
  79991. this._notifySelectedMeshUnselected();
  79992. this._currentMeshSelected = null;
  79993. this._teleportationAllowed = false;
  79994. this._hideTeleportationTarget();
  79995. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79996. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79997. }
  79998. };
  79999. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  80000. if (this._currentMeshSelected) {
  80001. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  80002. }
  80003. };
  80004. /**
  80005. * Sets the color of the laser ray from the vr controllers.
  80006. * @param color new color for the ray.
  80007. */
  80008. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  80009. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  80010. this._leftLaserPointer.material.emissiveColor = color;
  80011. }
  80012. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  80013. this._rightLaserPointer.material.emissiveColor = color;
  80014. }
  80015. };
  80016. /**
  80017. * Sets the color of the ray from the vr headsets gaze.
  80018. * @param color new color for the ray.
  80019. */
  80020. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  80021. if (this._gazeTracker.material) {
  80022. this._gazeTracker.material.emissiveColor = color;
  80023. }
  80024. };
  80025. /**
  80026. * Exits VR and disposes of the vr experience helper
  80027. */
  80028. VRExperienceHelper.prototype.dispose = function () {
  80029. if (this.isInVRMode) {
  80030. this.exitVR();
  80031. }
  80032. if (this._passProcessMove) {
  80033. this._passProcessMove.dispose();
  80034. }
  80035. if (this._postProcessMove) {
  80036. this._postProcessMove.dispose();
  80037. }
  80038. if (this._webVRCamera) {
  80039. this._webVRCamera.dispose();
  80040. }
  80041. if (this._vrDeviceOrientationCamera) {
  80042. this._vrDeviceOrientationCamera.dispose();
  80043. }
  80044. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  80045. document.body.removeChild(this._btnVR);
  80046. }
  80047. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  80048. this._deviceOrientationCamera.dispose();
  80049. }
  80050. if (this._gazeTracker) {
  80051. this._gazeTracker.dispose();
  80052. }
  80053. if (this._teleportationTarget) {
  80054. this._teleportationTarget.dispose();
  80055. }
  80056. this._floorMeshesCollection = [];
  80057. document.removeEventListener("keydown", this._onKeyDown);
  80058. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80059. window.removeEventListener("resize", this._onResize);
  80060. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  80061. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  80062. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  80063. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  80064. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  80065. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  80066. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  80067. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80068. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  80069. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  80070. this._scene.unregisterBeforeRender(this.beforeRender);
  80071. };
  80072. /**
  80073. * Gets the name of the VRExperienceHelper class
  80074. * @returns "VRExperienceHelper"
  80075. */
  80076. VRExperienceHelper.prototype.getClassName = function () {
  80077. return "VRExperienceHelper";
  80078. };
  80079. return VRExperienceHelper;
  80080. }());
  80081. BABYLON.VRExperienceHelper = VRExperienceHelper;
  80082. })(BABYLON || (BABYLON = {}));
  80083. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  80084. // Mainly based on these 2 articles :
  80085. // 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
  80086. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  80087. var BABYLON;
  80088. (function (BABYLON) {
  80089. var JoystickAxis;
  80090. (function (JoystickAxis) {
  80091. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  80092. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  80093. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  80094. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  80095. var VirtualJoystick = /** @class */ (function () {
  80096. function VirtualJoystick(leftJoystick) {
  80097. var _this = this;
  80098. if (leftJoystick) {
  80099. this._leftJoystick = true;
  80100. }
  80101. else {
  80102. this._leftJoystick = false;
  80103. }
  80104. VirtualJoystick._globalJoystickIndex++;
  80105. // By default left & right arrow keys are moving the X
  80106. // and up & down keys are moving the Y
  80107. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80108. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80109. this.reverseLeftRight = false;
  80110. this.reverseUpDown = false;
  80111. // collections of pointers
  80112. this._touches = new BABYLON.StringDictionary();
  80113. this.deltaPosition = BABYLON.Vector3.Zero();
  80114. this._joystickSensibility = 25;
  80115. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80116. this._onResize = function (evt) {
  80117. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80118. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80119. if (VirtualJoystick.vjCanvas) {
  80120. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  80121. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  80122. }
  80123. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  80124. };
  80125. // injecting a canvas element on top of the canvas 3D game
  80126. if (!VirtualJoystick.vjCanvas) {
  80127. window.addEventListener("resize", this._onResize, false);
  80128. VirtualJoystick.vjCanvas = document.createElement("canvas");
  80129. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80130. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80131. VirtualJoystick.vjCanvas.width = window.innerWidth;
  80132. VirtualJoystick.vjCanvas.height = window.innerHeight;
  80133. VirtualJoystick.vjCanvas.style.width = "100%";
  80134. VirtualJoystick.vjCanvas.style.height = "100%";
  80135. VirtualJoystick.vjCanvas.style.position = "absolute";
  80136. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  80137. VirtualJoystick.vjCanvas.style.top = "0px";
  80138. VirtualJoystick.vjCanvas.style.left = "0px";
  80139. VirtualJoystick.vjCanvas.style.zIndex = "5";
  80140. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  80141. // Support for jQuery PEP polyfill
  80142. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  80143. var context = VirtualJoystick.vjCanvas.getContext('2d');
  80144. if (!context) {
  80145. throw new Error("Unable to create canvas for virtual joystick");
  80146. }
  80147. VirtualJoystick.vjCanvasContext = context;
  80148. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  80149. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80150. document.body.appendChild(VirtualJoystick.vjCanvas);
  80151. }
  80152. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  80153. this.pressed = false;
  80154. // default joystick color
  80155. this._joystickColor = "cyan";
  80156. this._joystickPointerID = -1;
  80157. // current joystick position
  80158. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  80159. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  80160. // origin joystick position
  80161. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  80162. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  80163. this._onPointerDownHandlerRef = function (evt) {
  80164. _this._onPointerDown(evt);
  80165. };
  80166. this._onPointerMoveHandlerRef = function (evt) {
  80167. _this._onPointerMove(evt);
  80168. };
  80169. this._onPointerUpHandlerRef = function (evt) {
  80170. _this._onPointerUp(evt);
  80171. };
  80172. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  80173. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  80174. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  80175. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  80176. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  80177. evt.preventDefault(); // Disables system menu
  80178. }, false);
  80179. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80180. }
  80181. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  80182. this._joystickSensibility = newJoystickSensibility;
  80183. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80184. };
  80185. VirtualJoystick.prototype._onPointerDown = function (e) {
  80186. var positionOnScreenCondition;
  80187. e.preventDefault();
  80188. if (this._leftJoystick === true) {
  80189. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  80190. }
  80191. else {
  80192. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  80193. }
  80194. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  80195. // First contact will be dedicated to the virtual joystick
  80196. this._joystickPointerID = e.pointerId;
  80197. this._joystickPointerStartPos.x = e.clientX;
  80198. this._joystickPointerStartPos.y = e.clientY;
  80199. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  80200. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  80201. this._deltaJoystickVector.x = 0;
  80202. this._deltaJoystickVector.y = 0;
  80203. this.pressed = true;
  80204. this._touches.add(e.pointerId.toString(), e);
  80205. }
  80206. else {
  80207. // You can only trigger the action buttons with a joystick declared
  80208. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  80209. this._action();
  80210. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  80211. }
  80212. }
  80213. };
  80214. VirtualJoystick.prototype._onPointerMove = function (e) {
  80215. // If the current pointer is the one associated to the joystick (first touch contact)
  80216. if (this._joystickPointerID == e.pointerId) {
  80217. this._joystickPointerPos.x = e.clientX;
  80218. this._joystickPointerPos.y = e.clientY;
  80219. this._deltaJoystickVector = this._joystickPointerPos.clone();
  80220. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  80221. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  80222. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  80223. switch (this._axisTargetedByLeftAndRight) {
  80224. case JoystickAxis.X:
  80225. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  80226. break;
  80227. case JoystickAxis.Y:
  80228. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  80229. break;
  80230. case JoystickAxis.Z:
  80231. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  80232. break;
  80233. }
  80234. var directionUpDown = this.reverseUpDown ? 1 : -1;
  80235. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  80236. switch (this._axisTargetedByUpAndDown) {
  80237. case JoystickAxis.X:
  80238. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  80239. break;
  80240. case JoystickAxis.Y:
  80241. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  80242. break;
  80243. case JoystickAxis.Z:
  80244. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  80245. break;
  80246. }
  80247. }
  80248. else {
  80249. var data = this._touches.get(e.pointerId.toString());
  80250. if (data) {
  80251. data.x = e.clientX;
  80252. data.y = e.clientY;
  80253. }
  80254. }
  80255. };
  80256. VirtualJoystick.prototype._onPointerUp = function (e) {
  80257. if (this._joystickPointerID == e.pointerId) {
  80258. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  80259. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  80260. this._joystickPointerID = -1;
  80261. this.pressed = false;
  80262. }
  80263. else {
  80264. var touch = this._touches.get(e.pointerId.toString());
  80265. if (touch) {
  80266. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80267. }
  80268. }
  80269. this._deltaJoystickVector.x = 0;
  80270. this._deltaJoystickVector.y = 0;
  80271. this._touches.remove(e.pointerId.toString());
  80272. };
  80273. /**
  80274. * Change the color of the virtual joystick
  80275. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  80276. */
  80277. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  80278. this._joystickColor = newColor;
  80279. };
  80280. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  80281. this._action = action;
  80282. };
  80283. // Define which axis you'd like to control for left & right
  80284. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  80285. switch (axis) {
  80286. case JoystickAxis.X:
  80287. case JoystickAxis.Y:
  80288. case JoystickAxis.Z:
  80289. this._axisTargetedByLeftAndRight = axis;
  80290. break;
  80291. default:
  80292. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80293. break;
  80294. }
  80295. };
  80296. // Define which axis you'd like to control for up & down
  80297. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  80298. switch (axis) {
  80299. case JoystickAxis.X:
  80300. case JoystickAxis.Y:
  80301. case JoystickAxis.Z:
  80302. this._axisTargetedByUpAndDown = axis;
  80303. break;
  80304. default:
  80305. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80306. break;
  80307. }
  80308. };
  80309. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  80310. var _this = this;
  80311. if (this.pressed) {
  80312. this._touches.forEach(function (key, touch) {
  80313. if (touch.pointerId === _this._joystickPointerID) {
  80314. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  80315. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  80316. VirtualJoystick.vjCanvasContext.beginPath();
  80317. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80318. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80319. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  80320. VirtualJoystick.vjCanvasContext.stroke();
  80321. VirtualJoystick.vjCanvasContext.closePath();
  80322. VirtualJoystick.vjCanvasContext.beginPath();
  80323. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80324. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80325. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  80326. VirtualJoystick.vjCanvasContext.stroke();
  80327. VirtualJoystick.vjCanvasContext.closePath();
  80328. VirtualJoystick.vjCanvasContext.beginPath();
  80329. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80330. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  80331. VirtualJoystick.vjCanvasContext.stroke();
  80332. VirtualJoystick.vjCanvasContext.closePath();
  80333. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  80334. }
  80335. else {
  80336. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80337. VirtualJoystick.vjCanvasContext.beginPath();
  80338. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  80339. VirtualJoystick.vjCanvasContext.beginPath();
  80340. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  80341. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80342. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  80343. VirtualJoystick.vjCanvasContext.stroke();
  80344. VirtualJoystick.vjCanvasContext.closePath();
  80345. touch.prevX = touch.x;
  80346. touch.prevY = touch.y;
  80347. }
  80348. ;
  80349. });
  80350. }
  80351. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80352. };
  80353. VirtualJoystick.prototype.releaseCanvas = function () {
  80354. if (VirtualJoystick.vjCanvas) {
  80355. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  80356. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  80357. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  80358. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  80359. window.removeEventListener("resize", this._onResize);
  80360. document.body.removeChild(VirtualJoystick.vjCanvas);
  80361. VirtualJoystick.vjCanvas = null;
  80362. }
  80363. };
  80364. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  80365. VirtualJoystick._globalJoystickIndex = 0;
  80366. return VirtualJoystick;
  80367. }());
  80368. BABYLON.VirtualJoystick = VirtualJoystick;
  80369. })(BABYLON || (BABYLON = {}));
  80370. //# sourceMappingURL=babylon.virtualJoystick.js.map
  80371. var BABYLON;
  80372. (function (BABYLON) {
  80373. // We're mainly based on the logic defined into the FreeCamera code
  80374. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  80375. __extends(VirtualJoysticksCamera, _super);
  80376. function VirtualJoysticksCamera(name, position, scene) {
  80377. var _this = _super.call(this, name, position, scene) || this;
  80378. _this.inputs.addVirtualJoystick();
  80379. return _this;
  80380. }
  80381. VirtualJoysticksCamera.prototype.getClassName = function () {
  80382. return "VirtualJoysticksCamera";
  80383. };
  80384. return VirtualJoysticksCamera;
  80385. }(BABYLON.FreeCamera));
  80386. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  80387. })(BABYLON || (BABYLON = {}));
  80388. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  80389. var BABYLON;
  80390. (function (BABYLON) {
  80391. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  80392. function FreeCameraVirtualJoystickInput() {
  80393. }
  80394. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  80395. return this._leftjoystick;
  80396. };
  80397. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  80398. return this._rightjoystick;
  80399. };
  80400. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  80401. if (this._leftjoystick) {
  80402. var camera = this.camera;
  80403. var speed = camera._computeLocalCameraSpeed() * 50;
  80404. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  80405. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  80406. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  80407. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  80408. if (!this._leftjoystick.pressed) {
  80409. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  80410. }
  80411. if (!this._rightjoystick.pressed) {
  80412. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  80413. }
  80414. }
  80415. };
  80416. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  80417. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  80418. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  80419. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  80420. this._leftjoystick.setJoystickSensibility(0.15);
  80421. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  80422. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  80423. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  80424. this._rightjoystick.reverseUpDown = true;
  80425. this._rightjoystick.setJoystickSensibility(0.05);
  80426. this._rightjoystick.setJoystickColor("yellow");
  80427. };
  80428. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  80429. this._leftjoystick.releaseCanvas();
  80430. this._rightjoystick.releaseCanvas();
  80431. };
  80432. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  80433. return "FreeCameraVirtualJoystickInput";
  80434. };
  80435. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  80436. return "virtualJoystick";
  80437. };
  80438. return FreeCameraVirtualJoystickInput;
  80439. }());
  80440. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  80441. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  80442. })(BABYLON || (BABYLON = {}));
  80443. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  80444. var BABYLON;
  80445. (function (BABYLON) {
  80446. var SimplificationSettings = /** @class */ (function () {
  80447. function SimplificationSettings(quality, distance, optimizeMesh) {
  80448. this.quality = quality;
  80449. this.distance = distance;
  80450. this.optimizeMesh = optimizeMesh;
  80451. }
  80452. return SimplificationSettings;
  80453. }());
  80454. BABYLON.SimplificationSettings = SimplificationSettings;
  80455. var SimplificationQueue = /** @class */ (function () {
  80456. function SimplificationQueue() {
  80457. this.running = false;
  80458. this._simplificationArray = [];
  80459. }
  80460. SimplificationQueue.prototype.addTask = function (task) {
  80461. this._simplificationArray.push(task);
  80462. };
  80463. SimplificationQueue.prototype.executeNext = function () {
  80464. var task = this._simplificationArray.pop();
  80465. if (task) {
  80466. this.running = true;
  80467. this.runSimplification(task);
  80468. }
  80469. else {
  80470. this.running = false;
  80471. }
  80472. };
  80473. SimplificationQueue.prototype.runSimplification = function (task) {
  80474. var _this = this;
  80475. if (task.parallelProcessing) {
  80476. //parallel simplifier
  80477. task.settings.forEach(function (setting) {
  80478. var simplifier = _this.getSimplifier(task);
  80479. simplifier.simplify(setting, function (newMesh) {
  80480. task.mesh.addLODLevel(setting.distance, newMesh);
  80481. newMesh.isVisible = true;
  80482. //check if it is the last
  80483. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  80484. //all done, run the success callback.
  80485. task.successCallback();
  80486. }
  80487. _this.executeNext();
  80488. });
  80489. });
  80490. }
  80491. else {
  80492. //single simplifier.
  80493. var simplifier = this.getSimplifier(task);
  80494. var runDecimation = function (setting, callback) {
  80495. simplifier.simplify(setting, function (newMesh) {
  80496. task.mesh.addLODLevel(setting.distance, newMesh);
  80497. newMesh.isVisible = true;
  80498. //run the next quality level
  80499. callback();
  80500. });
  80501. };
  80502. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  80503. runDecimation(task.settings[loop.index], function () {
  80504. loop.executeNext();
  80505. });
  80506. }, function () {
  80507. //execution ended, run the success callback.
  80508. if (task.successCallback) {
  80509. task.successCallback();
  80510. }
  80511. _this.executeNext();
  80512. });
  80513. }
  80514. };
  80515. SimplificationQueue.prototype.getSimplifier = function (task) {
  80516. switch (task.simplificationType) {
  80517. case SimplificationType.QUADRATIC:
  80518. default:
  80519. return new QuadraticErrorSimplification(task.mesh);
  80520. }
  80521. };
  80522. return SimplificationQueue;
  80523. }());
  80524. BABYLON.SimplificationQueue = SimplificationQueue;
  80525. /**
  80526. * The implemented types of simplification.
  80527. * At the moment only Quadratic Error Decimation is implemented.
  80528. */
  80529. var SimplificationType;
  80530. (function (SimplificationType) {
  80531. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  80532. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  80533. var DecimationTriangle = /** @class */ (function () {
  80534. function DecimationTriangle(vertices) {
  80535. this.vertices = vertices;
  80536. this.error = new Array(4);
  80537. this.deleted = false;
  80538. this.isDirty = false;
  80539. this.deletePending = false;
  80540. this.borderFactor = 0;
  80541. }
  80542. return DecimationTriangle;
  80543. }());
  80544. BABYLON.DecimationTriangle = DecimationTriangle;
  80545. var DecimationVertex = /** @class */ (function () {
  80546. function DecimationVertex(position, id) {
  80547. this.position = position;
  80548. this.id = id;
  80549. this.isBorder = true;
  80550. this.q = new QuadraticMatrix();
  80551. this.triangleCount = 0;
  80552. this.triangleStart = 0;
  80553. this.originalOffsets = [];
  80554. }
  80555. DecimationVertex.prototype.updatePosition = function (newPosition) {
  80556. this.position.copyFrom(newPosition);
  80557. };
  80558. return DecimationVertex;
  80559. }());
  80560. BABYLON.DecimationVertex = DecimationVertex;
  80561. var QuadraticMatrix = /** @class */ (function () {
  80562. function QuadraticMatrix(data) {
  80563. this.data = new Array(10);
  80564. for (var i = 0; i < 10; ++i) {
  80565. if (data && data[i]) {
  80566. this.data[i] = data[i];
  80567. }
  80568. else {
  80569. this.data[i] = 0;
  80570. }
  80571. }
  80572. }
  80573. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  80574. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  80575. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  80576. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  80577. return det;
  80578. };
  80579. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  80580. for (var i = 0; i < 10; ++i) {
  80581. this.data[i] += matrix.data[i];
  80582. }
  80583. };
  80584. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  80585. for (var i = 0; i < 10; ++i) {
  80586. this.data[i] += data[i];
  80587. }
  80588. };
  80589. QuadraticMatrix.prototype.add = function (matrix) {
  80590. var m = new QuadraticMatrix();
  80591. for (var i = 0; i < 10; ++i) {
  80592. m.data[i] = this.data[i] + matrix.data[i];
  80593. }
  80594. return m;
  80595. };
  80596. QuadraticMatrix.FromData = function (a, b, c, d) {
  80597. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  80598. };
  80599. //returning an array to avoid garbage collection
  80600. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  80601. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  80602. };
  80603. return QuadraticMatrix;
  80604. }());
  80605. BABYLON.QuadraticMatrix = QuadraticMatrix;
  80606. var Reference = /** @class */ (function () {
  80607. function Reference(vertexId, triangleId) {
  80608. this.vertexId = vertexId;
  80609. this.triangleId = triangleId;
  80610. }
  80611. return Reference;
  80612. }());
  80613. BABYLON.Reference = Reference;
  80614. /**
  80615. * An implementation of the Quadratic Error simplification algorithm.
  80616. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  80617. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  80618. * @author RaananW
  80619. */
  80620. var QuadraticErrorSimplification = /** @class */ (function () {
  80621. function QuadraticErrorSimplification(_mesh) {
  80622. this._mesh = _mesh;
  80623. this.syncIterations = 5000;
  80624. this.aggressiveness = 7;
  80625. this.decimationIterations = 100;
  80626. this.boundingBoxEpsilon = BABYLON.Epsilon;
  80627. }
  80628. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  80629. var _this = this;
  80630. this.initDecimatedMesh();
  80631. //iterating through the submeshes array, one after the other.
  80632. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  80633. _this.initWithMesh(loop.index, function () {
  80634. _this.runDecimation(settings, loop.index, function () {
  80635. loop.executeNext();
  80636. });
  80637. }, settings.optimizeMesh);
  80638. }, function () {
  80639. setTimeout(function () {
  80640. successCallback(_this._reconstructedMesh);
  80641. }, 0);
  80642. });
  80643. };
  80644. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  80645. var _this = this;
  80646. var targetCount = ~~(this.triangles.length * settings.quality);
  80647. var deletedTriangles = 0;
  80648. var triangleCount = this.triangles.length;
  80649. var iterationFunction = function (iteration, callback) {
  80650. setTimeout(function () {
  80651. if (iteration % 5 === 0) {
  80652. _this.updateMesh(iteration === 0);
  80653. }
  80654. for (var i = 0; i < _this.triangles.length; ++i) {
  80655. _this.triangles[i].isDirty = false;
  80656. }
  80657. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  80658. var trianglesIterator = function (i) {
  80659. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  80660. var t = _this.triangles[tIdx];
  80661. if (!t)
  80662. return;
  80663. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  80664. return;
  80665. }
  80666. for (var j = 0; j < 3; ++j) {
  80667. if (t.error[j] < threshold) {
  80668. var deleted0 = [];
  80669. var deleted1 = [];
  80670. var v0 = t.vertices[j];
  80671. var v1 = t.vertices[(j + 1) % 3];
  80672. if (v0.isBorder || v1.isBorder)
  80673. continue;
  80674. var p = BABYLON.Vector3.Zero();
  80675. var n = BABYLON.Vector3.Zero();
  80676. var uv = BABYLON.Vector2.Zero();
  80677. var color = new BABYLON.Color4(0, 0, 0, 1);
  80678. _this.calculateError(v0, v1, p, n, uv, color);
  80679. var delTr = new Array();
  80680. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  80681. continue;
  80682. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  80683. continue;
  80684. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  80685. continue;
  80686. var uniqueArray = new Array();
  80687. delTr.forEach(function (deletedT) {
  80688. if (uniqueArray.indexOf(deletedT) === -1) {
  80689. deletedT.deletePending = true;
  80690. uniqueArray.push(deletedT);
  80691. }
  80692. });
  80693. if (uniqueArray.length % 2 !== 0) {
  80694. continue;
  80695. }
  80696. v0.q = v1.q.add(v0.q);
  80697. v0.updatePosition(p);
  80698. var tStart = _this.references.length;
  80699. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  80700. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  80701. var tCount = _this.references.length - tStart;
  80702. if (tCount <= v0.triangleCount) {
  80703. if (tCount) {
  80704. for (var c = 0; c < tCount; c++) {
  80705. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  80706. }
  80707. }
  80708. }
  80709. else {
  80710. v0.triangleStart = tStart;
  80711. }
  80712. v0.triangleCount = tCount;
  80713. break;
  80714. }
  80715. }
  80716. };
  80717. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  80718. }, 0);
  80719. };
  80720. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  80721. if (triangleCount - deletedTriangles <= targetCount)
  80722. loop.breakLoop();
  80723. else {
  80724. iterationFunction(loop.index, function () {
  80725. loop.executeNext();
  80726. });
  80727. }
  80728. }, function () {
  80729. setTimeout(function () {
  80730. //reconstruct this part of the mesh
  80731. _this.reconstructMesh(submeshIndex);
  80732. successCallback();
  80733. }, 0);
  80734. });
  80735. };
  80736. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  80737. var _this = this;
  80738. this.vertices = [];
  80739. this.triangles = [];
  80740. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  80741. var indices = this._mesh.getIndices();
  80742. var submesh = this._mesh.subMeshes[submeshIndex];
  80743. var findInVertices = function (positionToSearch) {
  80744. if (optimizeMesh) {
  80745. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  80746. if (_this.vertices[ii].position.equals(positionToSearch)) {
  80747. return _this.vertices[ii];
  80748. }
  80749. }
  80750. }
  80751. return null;
  80752. };
  80753. var vertexReferences = [];
  80754. var vertexInit = function (i) {
  80755. if (!positionData) {
  80756. return;
  80757. }
  80758. var offset = i + submesh.verticesStart;
  80759. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  80760. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  80761. vertex.originalOffsets.push(offset);
  80762. if (vertex.id === _this.vertices.length) {
  80763. _this.vertices.push(vertex);
  80764. }
  80765. vertexReferences.push(vertex.id);
  80766. };
  80767. //var totalVertices = mesh.getTotalVertices();
  80768. var totalVertices = submesh.verticesCount;
  80769. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  80770. var indicesInit = function (i) {
  80771. if (!indices) {
  80772. return;
  80773. }
  80774. var offset = (submesh.indexStart / 3) + i;
  80775. var pos = (offset * 3);
  80776. var i0 = indices[pos + 0];
  80777. var i1 = indices[pos + 1];
  80778. var i2 = indices[pos + 2];
  80779. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  80780. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  80781. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  80782. var triangle = new DecimationTriangle([v0, v1, v2]);
  80783. triangle.originalOffset = pos;
  80784. _this.triangles.push(triangle);
  80785. };
  80786. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  80787. _this.init(callback);
  80788. });
  80789. });
  80790. };
  80791. QuadraticErrorSimplification.prototype.init = function (callback) {
  80792. var _this = this;
  80793. var triangleInit1 = function (i) {
  80794. var t = _this.triangles[i];
  80795. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  80796. for (var j = 0; j < 3; j++) {
  80797. 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))));
  80798. }
  80799. };
  80800. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  80801. var triangleInit2 = function (i) {
  80802. var t = _this.triangles[i];
  80803. for (var j = 0; j < 3; ++j) {
  80804. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  80805. }
  80806. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80807. };
  80808. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  80809. callback();
  80810. });
  80811. });
  80812. };
  80813. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  80814. var newTriangles = [];
  80815. var i;
  80816. for (i = 0; i < this.vertices.length; ++i) {
  80817. this.vertices[i].triangleCount = 0;
  80818. }
  80819. var t;
  80820. var j;
  80821. for (i = 0; i < this.triangles.length; ++i) {
  80822. if (!this.triangles[i].deleted) {
  80823. t = this.triangles[i];
  80824. for (j = 0; j < 3; ++j) {
  80825. t.vertices[j].triangleCount = 1;
  80826. }
  80827. newTriangles.push(t);
  80828. }
  80829. }
  80830. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  80831. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  80832. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  80833. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  80834. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  80835. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80836. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  80837. var vertexCount = 0;
  80838. for (i = 0; i < this.vertices.length; ++i) {
  80839. var vertex = this.vertices[i];
  80840. vertex.id = vertexCount;
  80841. if (vertex.triangleCount) {
  80842. vertex.originalOffsets.forEach(function (originalOffset) {
  80843. if (!normalData) {
  80844. return;
  80845. }
  80846. newPositionData.push(vertex.position.x);
  80847. newPositionData.push(vertex.position.y);
  80848. newPositionData.push(vertex.position.z);
  80849. newNormalData.push(normalData[originalOffset * 3]);
  80850. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  80851. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  80852. if (uvs && uvs.length) {
  80853. newUVsData.push(uvs[(originalOffset * 2)]);
  80854. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  80855. }
  80856. else if (colorsData && colorsData.length) {
  80857. newColorsData.push(colorsData[(originalOffset * 4)]);
  80858. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  80859. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  80860. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  80861. }
  80862. ++vertexCount;
  80863. });
  80864. }
  80865. }
  80866. var startingIndex = this._reconstructedMesh.getTotalIndices();
  80867. var startingVertex = this._reconstructedMesh.getTotalVertices();
  80868. var submeshesArray = this._reconstructedMesh.subMeshes;
  80869. this._reconstructedMesh.subMeshes = [];
  80870. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  80871. var originalIndices = this._mesh.getIndices();
  80872. for (i = 0; i < newTriangles.length; ++i) {
  80873. t = newTriangles[i]; //now get the new referencing point for each vertex
  80874. [0, 1, 2].forEach(function (idx) {
  80875. var id = originalIndices[t.originalOffset + idx];
  80876. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  80877. if (offset < 0)
  80878. offset = 0;
  80879. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  80880. });
  80881. }
  80882. //overwriting the old vertex buffers and indices.
  80883. this._reconstructedMesh.setIndices(newIndicesArray);
  80884. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  80885. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  80886. if (newUVsData.length > 0)
  80887. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  80888. if (newColorsData.length > 0)
  80889. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  80890. //create submesh
  80891. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  80892. if (submeshIndex > 0) {
  80893. this._reconstructedMesh.subMeshes = [];
  80894. submeshesArray.forEach(function (submesh) {
  80895. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  80896. });
  80897. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  80898. }
  80899. };
  80900. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  80901. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  80902. this._reconstructedMesh.material = this._mesh.material;
  80903. this._reconstructedMesh.parent = this._mesh.parent;
  80904. this._reconstructedMesh.isVisible = false;
  80905. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  80906. };
  80907. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  80908. for (var i = 0; i < vertex1.triangleCount; ++i) {
  80909. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  80910. if (t.deleted)
  80911. continue;
  80912. var s = this.references[vertex1.triangleStart + i].vertexId;
  80913. var v1 = t.vertices[(s + 1) % 3];
  80914. var v2 = t.vertices[(s + 2) % 3];
  80915. if ((v1 === vertex2 || v2 === vertex2)) {
  80916. deletedArray[i] = true;
  80917. delTr.push(t);
  80918. continue;
  80919. }
  80920. var d1 = v1.position.subtract(point);
  80921. d1 = d1.normalize();
  80922. var d2 = v2.position.subtract(point);
  80923. d2 = d2.normalize();
  80924. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  80925. return true;
  80926. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  80927. deletedArray[i] = false;
  80928. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  80929. return true;
  80930. }
  80931. return false;
  80932. };
  80933. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  80934. var newDeleted = deletedTriangles;
  80935. for (var i = 0; i < vertex.triangleCount; ++i) {
  80936. var ref = this.references[vertex.triangleStart + i];
  80937. var t = this.triangles[ref.triangleId];
  80938. if (t.deleted)
  80939. continue;
  80940. if (deletedArray[i] && t.deletePending) {
  80941. t.deleted = true;
  80942. newDeleted++;
  80943. continue;
  80944. }
  80945. t.vertices[ref.vertexId] = origVertex;
  80946. t.isDirty = true;
  80947. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  80948. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  80949. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  80950. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80951. this.references.push(ref);
  80952. }
  80953. return newDeleted;
  80954. };
  80955. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  80956. for (var i = 0; i < this.vertices.length; ++i) {
  80957. var vCount = [];
  80958. var vId = [];
  80959. var v = this.vertices[i];
  80960. var j;
  80961. for (j = 0; j < v.triangleCount; ++j) {
  80962. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  80963. for (var ii = 0; ii < 3; ii++) {
  80964. var ofs = 0;
  80965. var vv = triangle.vertices[ii];
  80966. while (ofs < vCount.length) {
  80967. if (vId[ofs] === vv.id)
  80968. break;
  80969. ++ofs;
  80970. }
  80971. if (ofs === vCount.length) {
  80972. vCount.push(1);
  80973. vId.push(vv.id);
  80974. }
  80975. else {
  80976. vCount[ofs]++;
  80977. }
  80978. }
  80979. }
  80980. for (j = 0; j < vCount.length; ++j) {
  80981. if (vCount[j] === 1) {
  80982. this.vertices[vId[j]].isBorder = true;
  80983. }
  80984. else {
  80985. this.vertices[vId[j]].isBorder = false;
  80986. }
  80987. }
  80988. }
  80989. };
  80990. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  80991. if (identifyBorders === void 0) { identifyBorders = false; }
  80992. var i;
  80993. if (!identifyBorders) {
  80994. var newTrianglesVector = [];
  80995. for (i = 0; i < this.triangles.length; ++i) {
  80996. if (!this.triangles[i].deleted) {
  80997. newTrianglesVector.push(this.triangles[i]);
  80998. }
  80999. }
  81000. this.triangles = newTrianglesVector;
  81001. }
  81002. for (i = 0; i < this.vertices.length; ++i) {
  81003. this.vertices[i].triangleCount = 0;
  81004. this.vertices[i].triangleStart = 0;
  81005. }
  81006. var t;
  81007. var j;
  81008. var v;
  81009. for (i = 0; i < this.triangles.length; ++i) {
  81010. t = this.triangles[i];
  81011. for (j = 0; j < 3; ++j) {
  81012. v = t.vertices[j];
  81013. v.triangleCount++;
  81014. }
  81015. }
  81016. var tStart = 0;
  81017. for (i = 0; i < this.vertices.length; ++i) {
  81018. this.vertices[i].triangleStart = tStart;
  81019. tStart += this.vertices[i].triangleCount;
  81020. this.vertices[i].triangleCount = 0;
  81021. }
  81022. var newReferences = new Array(this.triangles.length * 3);
  81023. for (i = 0; i < this.triangles.length; ++i) {
  81024. t = this.triangles[i];
  81025. for (j = 0; j < 3; ++j) {
  81026. v = t.vertices[j];
  81027. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  81028. v.triangleCount++;
  81029. }
  81030. }
  81031. this.references = newReferences;
  81032. if (identifyBorders) {
  81033. this.identifyBorder();
  81034. }
  81035. };
  81036. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  81037. var x = point.x;
  81038. var y = point.y;
  81039. var z = point.z;
  81040. 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
  81041. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  81042. };
  81043. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  81044. var q = vertex1.q.add(vertex2.q);
  81045. var border = vertex1.isBorder && vertex2.isBorder;
  81046. var error = 0;
  81047. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  81048. if (qDet !== 0 && !border) {
  81049. if (!pointResult) {
  81050. pointResult = BABYLON.Vector3.Zero();
  81051. }
  81052. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  81053. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  81054. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  81055. error = this.vertexError(q, pointResult);
  81056. }
  81057. else {
  81058. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  81059. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  81060. var error1 = this.vertexError(q, vertex1.position);
  81061. var error2 = this.vertexError(q, vertex2.position);
  81062. var error3 = this.vertexError(q, p3);
  81063. error = Math.min(error1, error2, error3);
  81064. if (error === error1) {
  81065. if (pointResult) {
  81066. pointResult.copyFrom(vertex1.position);
  81067. }
  81068. }
  81069. else if (error === error2) {
  81070. if (pointResult) {
  81071. pointResult.copyFrom(vertex2.position);
  81072. }
  81073. }
  81074. else {
  81075. if (pointResult) {
  81076. pointResult.copyFrom(p3);
  81077. }
  81078. }
  81079. }
  81080. return error;
  81081. };
  81082. return QuadraticErrorSimplification;
  81083. }());
  81084. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  81085. })(BABYLON || (BABYLON = {}));
  81086. //# sourceMappingURL=babylon.meshSimplification.js.map
  81087. var BABYLON;
  81088. (function (BABYLON) {
  81089. var MeshLODLevel = /** @class */ (function () {
  81090. function MeshLODLevel(distance, mesh) {
  81091. this.distance = distance;
  81092. this.mesh = mesh;
  81093. }
  81094. return MeshLODLevel;
  81095. }());
  81096. BABYLON.MeshLODLevel = MeshLODLevel;
  81097. })(BABYLON || (BABYLON = {}));
  81098. //# sourceMappingURL=babylon.meshLODLevel.js.map
  81099. var BABYLON;
  81100. (function (BABYLON) {
  81101. /**
  81102. * Defines the root class used to create scene optimization to use with SceneOptimizer
  81103. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81104. */
  81105. var SceneOptimization = /** @class */ (function () {
  81106. /**
  81107. * Creates the SceneOptimization object
  81108. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81109. * @param desc defines the description associated with the optimization
  81110. */
  81111. function SceneOptimization(
  81112. /**
  81113. * Defines the priority of this optimization (0 by default which means first in the list)
  81114. */
  81115. priority) {
  81116. if (priority === void 0) { priority = 0; }
  81117. this.priority = priority;
  81118. }
  81119. /**
  81120. * Gets a string describing the action executed by the current optimization
  81121. * @returns description string
  81122. */
  81123. SceneOptimization.prototype.getDescription = function () {
  81124. return "";
  81125. };
  81126. /**
  81127. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81128. * @param scene defines the current scene where to apply this optimization
  81129. * @param optimizer defines the current optimizer
  81130. * @returns true if everything that can be done was applied
  81131. */
  81132. SceneOptimization.prototype.apply = function (scene, optimizer) {
  81133. return true;
  81134. };
  81135. ;
  81136. return SceneOptimization;
  81137. }());
  81138. BABYLON.SceneOptimization = SceneOptimization;
  81139. /**
  81140. * Defines an optimization used to reduce the size of render target textures
  81141. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81142. */
  81143. var TextureOptimization = /** @class */ (function (_super) {
  81144. __extends(TextureOptimization, _super);
  81145. /**
  81146. * Creates the TextureOptimization object
  81147. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81148. * @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
  81149. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81150. */
  81151. function TextureOptimization(
  81152. /**
  81153. * Defines the priority of this optimization (0 by default which means first in the list)
  81154. */
  81155. priority,
  81156. /**
  81157. * 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
  81158. */
  81159. maximumSize,
  81160. /**
  81161. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81162. */
  81163. step) {
  81164. if (priority === void 0) { priority = 0; }
  81165. if (maximumSize === void 0) { maximumSize = 1024; }
  81166. if (step === void 0) { step = 0.5; }
  81167. var _this = _super.call(this, priority) || this;
  81168. _this.priority = priority;
  81169. _this.maximumSize = maximumSize;
  81170. _this.step = step;
  81171. return _this;
  81172. }
  81173. /**
  81174. * Gets a string describing the action executed by the current optimization
  81175. * @returns description string
  81176. */
  81177. TextureOptimization.prototype.getDescription = function () {
  81178. return "Reducing render target texture size to " + this.maximumSize;
  81179. };
  81180. /**
  81181. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81182. * @param scene defines the current scene where to apply this optimization
  81183. * @param optimizer defines the current optimizer
  81184. * @returns true if everything that can be done was applied
  81185. */
  81186. TextureOptimization.prototype.apply = function (scene, optimizer) {
  81187. var allDone = true;
  81188. for (var index = 0; index < scene.textures.length; index++) {
  81189. var texture = scene.textures[index];
  81190. if (!texture.canRescale || texture.getContext) {
  81191. continue;
  81192. }
  81193. var currentSize = texture.getSize();
  81194. var maxDimension = Math.max(currentSize.width, currentSize.height);
  81195. if (maxDimension > this.maximumSize) {
  81196. texture.scale(this.step);
  81197. allDone = false;
  81198. }
  81199. }
  81200. return allDone;
  81201. };
  81202. return TextureOptimization;
  81203. }(SceneOptimization));
  81204. BABYLON.TextureOptimization = TextureOptimization;
  81205. /**
  81206. * Defines an optimization used to increase or decrease the rendering resolution
  81207. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81208. */
  81209. var HardwareScalingOptimization = /** @class */ (function (_super) {
  81210. __extends(HardwareScalingOptimization, _super);
  81211. /**
  81212. * Creates the HardwareScalingOptimization object
  81213. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81214. * @param maximumScale defines the maximum scale to use (2 by default)
  81215. * @param step defines the step to use between two passes (0.5 by default)
  81216. */
  81217. function HardwareScalingOptimization(
  81218. /**
  81219. * Defines the priority of this optimization (0 by default which means first in the list)
  81220. */
  81221. priority,
  81222. /**
  81223. * Defines the maximum scale to use (2 by default)
  81224. */
  81225. maximumScale,
  81226. /**
  81227. * Defines the step to use between two passes (0.5 by default)
  81228. */
  81229. step) {
  81230. if (priority === void 0) { priority = 0; }
  81231. if (maximumScale === void 0) { maximumScale = 2; }
  81232. if (step === void 0) { step = 0.25; }
  81233. var _this = _super.call(this, priority) || this;
  81234. _this.priority = priority;
  81235. _this.maximumScale = maximumScale;
  81236. _this.step = step;
  81237. _this._currentScale = -1;
  81238. _this._directionOffset = 1;
  81239. return _this;
  81240. }
  81241. /**
  81242. * Gets a string describing the action executed by the current optimization
  81243. * @return description string
  81244. */
  81245. HardwareScalingOptimization.prototype.getDescription = function () {
  81246. return "Setting hardware scaling level to " + this._currentScale;
  81247. };
  81248. /**
  81249. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81250. * @param scene defines the current scene where to apply this optimization
  81251. * @param optimizer defines the current optimizer
  81252. * @returns true if everything that can be done was applied
  81253. */
  81254. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  81255. if (this._currentScale === -1) {
  81256. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  81257. if (this._currentScale > this.maximumScale) {
  81258. this._directionOffset = -1;
  81259. }
  81260. }
  81261. this._currentScale += this._directionOffset * this.step;
  81262. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  81263. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  81264. };
  81265. ;
  81266. return HardwareScalingOptimization;
  81267. }(SceneOptimization));
  81268. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  81269. /**
  81270. * Defines an optimization used to remove shadows
  81271. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81272. */
  81273. var ShadowsOptimization = /** @class */ (function (_super) {
  81274. __extends(ShadowsOptimization, _super);
  81275. function ShadowsOptimization() {
  81276. return _super !== null && _super.apply(this, arguments) || this;
  81277. }
  81278. /**
  81279. * Gets a string describing the action executed by the current optimization
  81280. * @return description string
  81281. */
  81282. ShadowsOptimization.prototype.getDescription = function () {
  81283. return "Turning shadows on/off";
  81284. };
  81285. /**
  81286. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81287. * @param scene defines the current scene where to apply this optimization
  81288. * @param optimizer defines the current optimizer
  81289. * @returns true if everything that can be done was applied
  81290. */
  81291. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  81292. scene.shadowsEnabled = optimizer.isInImprovementMode;
  81293. return true;
  81294. };
  81295. ;
  81296. return ShadowsOptimization;
  81297. }(SceneOptimization));
  81298. BABYLON.ShadowsOptimization = ShadowsOptimization;
  81299. /**
  81300. * Defines an optimization used to turn post-processes off
  81301. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81302. */
  81303. var PostProcessesOptimization = /** @class */ (function (_super) {
  81304. __extends(PostProcessesOptimization, _super);
  81305. function PostProcessesOptimization() {
  81306. return _super !== null && _super.apply(this, arguments) || this;
  81307. }
  81308. /**
  81309. * Gets a string describing the action executed by the current optimization
  81310. * @return description string
  81311. */
  81312. PostProcessesOptimization.prototype.getDescription = function () {
  81313. return "Turning post-processes on/off";
  81314. };
  81315. /**
  81316. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81317. * @param scene defines the current scene where to apply this optimization
  81318. * @param optimizer defines the current optimizer
  81319. * @returns true if everything that can be done was applied
  81320. */
  81321. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  81322. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  81323. return true;
  81324. };
  81325. ;
  81326. return PostProcessesOptimization;
  81327. }(SceneOptimization));
  81328. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  81329. /**
  81330. * Defines an optimization used to turn lens flares off
  81331. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81332. */
  81333. var LensFlaresOptimization = /** @class */ (function (_super) {
  81334. __extends(LensFlaresOptimization, _super);
  81335. function LensFlaresOptimization() {
  81336. return _super !== null && _super.apply(this, arguments) || this;
  81337. }
  81338. /**
  81339. * Gets a string describing the action executed by the current optimization
  81340. * @return description string
  81341. */
  81342. LensFlaresOptimization.prototype.getDescription = function () {
  81343. return "Turning lens flares on/off";
  81344. };
  81345. /**
  81346. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81347. * @param scene defines the current scene where to apply this optimization
  81348. * @param optimizer defines the current optimizer
  81349. * @returns true if everything that can be done was applied
  81350. */
  81351. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  81352. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  81353. return true;
  81354. };
  81355. ;
  81356. return LensFlaresOptimization;
  81357. }(SceneOptimization));
  81358. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  81359. /**
  81360. * Defines an optimization based on user defined callback.
  81361. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81362. */
  81363. var CustomOptimization = /** @class */ (function (_super) {
  81364. __extends(CustomOptimization, _super);
  81365. function CustomOptimization() {
  81366. return _super !== null && _super.apply(this, arguments) || this;
  81367. }
  81368. /**
  81369. * Gets a string describing the action executed by the current optimization
  81370. * @returns description string
  81371. */
  81372. CustomOptimization.prototype.getDescription = function () {
  81373. if (this.onGetDescription) {
  81374. return this.onGetDescription();
  81375. }
  81376. return "Running user defined callback";
  81377. };
  81378. /**
  81379. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81380. * @param scene defines the current scene where to apply this optimization
  81381. * @param optimizer defines the current optimizer
  81382. * @returns true if everything that can be done was applied
  81383. */
  81384. CustomOptimization.prototype.apply = function (scene, optimizer) {
  81385. if (this.onApply) {
  81386. return this.onApply(scene, optimizer);
  81387. }
  81388. return true;
  81389. };
  81390. ;
  81391. return CustomOptimization;
  81392. }(SceneOptimization));
  81393. BABYLON.CustomOptimization = CustomOptimization;
  81394. /**
  81395. * Defines an optimization used to turn particles off
  81396. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81397. */
  81398. var ParticlesOptimization = /** @class */ (function (_super) {
  81399. __extends(ParticlesOptimization, _super);
  81400. function ParticlesOptimization() {
  81401. return _super !== null && _super.apply(this, arguments) || this;
  81402. }
  81403. /**
  81404. * Gets a string describing the action executed by the current optimization
  81405. * @return description string
  81406. */
  81407. ParticlesOptimization.prototype.getDescription = function () {
  81408. return "Turning particles on/off";
  81409. };
  81410. /**
  81411. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81412. * @param scene defines the current scene where to apply this optimization
  81413. * @param optimizer defines the current optimizer
  81414. * @returns true if everything that can be done was applied
  81415. */
  81416. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  81417. scene.particlesEnabled = optimizer.isInImprovementMode;
  81418. return true;
  81419. };
  81420. ;
  81421. return ParticlesOptimization;
  81422. }(SceneOptimization));
  81423. BABYLON.ParticlesOptimization = ParticlesOptimization;
  81424. /**
  81425. * Defines an optimization used to turn render targets off
  81426. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81427. */
  81428. var RenderTargetsOptimization = /** @class */ (function (_super) {
  81429. __extends(RenderTargetsOptimization, _super);
  81430. function RenderTargetsOptimization() {
  81431. return _super !== null && _super.apply(this, arguments) || this;
  81432. }
  81433. /**
  81434. * Gets a string describing the action executed by the current optimization
  81435. * @return description string
  81436. */
  81437. RenderTargetsOptimization.prototype.getDescription = function () {
  81438. return "Turning render targets off";
  81439. };
  81440. /**
  81441. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81442. * @param scene defines the current scene where to apply this optimization
  81443. * @param optimizer defines the current optimizer
  81444. * @returns true if everything that can be done was applied
  81445. */
  81446. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  81447. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  81448. return true;
  81449. };
  81450. ;
  81451. return RenderTargetsOptimization;
  81452. }(SceneOptimization));
  81453. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  81454. /**
  81455. * Defines an optimization used to merge meshes with compatible materials
  81456. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81457. */
  81458. var MergeMeshesOptimization = /** @class */ (function (_super) {
  81459. __extends(MergeMeshesOptimization, _super);
  81460. function MergeMeshesOptimization() {
  81461. var _this = _super !== null && _super.apply(this, arguments) || this;
  81462. _this._canBeMerged = function (abstractMesh) {
  81463. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  81464. return false;
  81465. }
  81466. var mesh = abstractMesh;
  81467. if (!mesh.isVisible || !mesh.isEnabled()) {
  81468. return false;
  81469. }
  81470. if (mesh.instances.length > 0) {
  81471. return false;
  81472. }
  81473. if (mesh.skeleton || mesh.hasLODLevels) {
  81474. return false;
  81475. }
  81476. if (mesh.parent) {
  81477. return false;
  81478. }
  81479. return true;
  81480. };
  81481. return _this;
  81482. }
  81483. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  81484. /**
  81485. * Gets or sets a boolean which defines if optimization octree has to be updated
  81486. */
  81487. get: function () {
  81488. return MergeMeshesOptimization._UpdateSelectionTree;
  81489. },
  81490. /**
  81491. * Gets or sets a boolean which defines if optimization octree has to be updated
  81492. */
  81493. set: function (value) {
  81494. MergeMeshesOptimization._UpdateSelectionTree = value;
  81495. },
  81496. enumerable: true,
  81497. configurable: true
  81498. });
  81499. /**
  81500. * Gets a string describing the action executed by the current optimization
  81501. * @return description string
  81502. */
  81503. MergeMeshesOptimization.prototype.getDescription = function () {
  81504. return "Merging similar meshes together";
  81505. };
  81506. /**
  81507. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81508. * @param scene defines the current scene where to apply this optimization
  81509. * @param optimizer defines the current optimizer
  81510. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  81511. * @returns true if everything that can be done was applied
  81512. */
  81513. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  81514. var globalPool = scene.meshes.slice(0);
  81515. var globalLength = globalPool.length;
  81516. for (var index = 0; index < globalLength; index++) {
  81517. var currentPool = new Array();
  81518. var current = globalPool[index];
  81519. // Checks
  81520. if (!this._canBeMerged(current)) {
  81521. continue;
  81522. }
  81523. currentPool.push(current);
  81524. // Find compatible meshes
  81525. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  81526. var otherMesh = globalPool[subIndex];
  81527. if (!this._canBeMerged(otherMesh)) {
  81528. continue;
  81529. }
  81530. if (otherMesh.material !== current.material) {
  81531. continue;
  81532. }
  81533. if (otherMesh.checkCollisions !== current.checkCollisions) {
  81534. continue;
  81535. }
  81536. currentPool.push(otherMesh);
  81537. globalLength--;
  81538. globalPool.splice(subIndex, 1);
  81539. subIndex--;
  81540. }
  81541. if (currentPool.length < 2) {
  81542. continue;
  81543. }
  81544. // Merge meshes
  81545. BABYLON.Mesh.MergeMeshes(currentPool);
  81546. }
  81547. if (updateSelectionTree != undefined) {
  81548. if (updateSelectionTree) {
  81549. scene.createOrUpdateSelectionOctree();
  81550. }
  81551. }
  81552. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  81553. scene.createOrUpdateSelectionOctree();
  81554. }
  81555. return true;
  81556. };
  81557. ;
  81558. MergeMeshesOptimization._UpdateSelectionTree = false;
  81559. return MergeMeshesOptimization;
  81560. }(SceneOptimization));
  81561. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  81562. /**
  81563. * Defines a list of options used by SceneOptimizer
  81564. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81565. */
  81566. var SceneOptimizerOptions = /** @class */ (function () {
  81567. /**
  81568. * Creates a new list of options used by SceneOptimizer
  81569. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  81570. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  81571. */
  81572. function SceneOptimizerOptions(
  81573. /**
  81574. * Defines the target frame rate to reach (60 by default)
  81575. */
  81576. targetFrameRate,
  81577. /**
  81578. * Defines the interval between two checkes (2000ms by default)
  81579. */
  81580. trackerDuration) {
  81581. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  81582. if (trackerDuration === void 0) { trackerDuration = 2000; }
  81583. this.targetFrameRate = targetFrameRate;
  81584. this.trackerDuration = trackerDuration;
  81585. /**
  81586. * Gets the list of optimizations to apply
  81587. */
  81588. this.optimizations = new Array();
  81589. }
  81590. /**
  81591. * Add a new optimization
  81592. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  81593. * @returns the current SceneOptimizerOptions
  81594. */
  81595. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  81596. this.optimizations.push(optimization);
  81597. return this;
  81598. };
  81599. /**
  81600. * Add a new custom optimization
  81601. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  81602. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  81603. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81604. * @returns the current SceneOptimizerOptions
  81605. */
  81606. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  81607. if (priority === void 0) { priority = 0; }
  81608. var optimization = new CustomOptimization(priority);
  81609. optimization.onApply = onApply;
  81610. optimization.onGetDescription = onGetDescription;
  81611. this.optimizations.push(optimization);
  81612. return this;
  81613. };
  81614. /**
  81615. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  81616. * @param targetFrameRate defines the target frame rate (60 by default)
  81617. * @returns a SceneOptimizerOptions object
  81618. */
  81619. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  81620. var result = new SceneOptimizerOptions(targetFrameRate);
  81621. var priority = 0;
  81622. result.addOptimization(new MergeMeshesOptimization(priority));
  81623. result.addOptimization(new ShadowsOptimization(priority));
  81624. result.addOptimization(new LensFlaresOptimization(priority));
  81625. // Next priority
  81626. priority++;
  81627. result.addOptimization(new PostProcessesOptimization(priority));
  81628. result.addOptimization(new ParticlesOptimization(priority));
  81629. // Next priority
  81630. priority++;
  81631. result.addOptimization(new TextureOptimization(priority, 1024));
  81632. return result;
  81633. };
  81634. /**
  81635. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  81636. * @param targetFrameRate defines the target frame rate (60 by default)
  81637. * @returns a SceneOptimizerOptions object
  81638. */
  81639. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  81640. var result = new SceneOptimizerOptions(targetFrameRate);
  81641. var priority = 0;
  81642. result.addOptimization(new MergeMeshesOptimization(priority));
  81643. result.addOptimization(new ShadowsOptimization(priority));
  81644. result.addOptimization(new LensFlaresOptimization(priority));
  81645. // Next priority
  81646. priority++;
  81647. result.addOptimization(new PostProcessesOptimization(priority));
  81648. result.addOptimization(new ParticlesOptimization(priority));
  81649. // Next priority
  81650. priority++;
  81651. result.addOptimization(new TextureOptimization(priority, 512));
  81652. // Next priority
  81653. priority++;
  81654. result.addOptimization(new RenderTargetsOptimization(priority));
  81655. // Next priority
  81656. priority++;
  81657. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  81658. return result;
  81659. };
  81660. /**
  81661. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  81662. * @param targetFrameRate defines the target frame rate (60 by default)
  81663. * @returns a SceneOptimizerOptions object
  81664. */
  81665. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  81666. var result = new SceneOptimizerOptions(targetFrameRate);
  81667. var priority = 0;
  81668. result.addOptimization(new MergeMeshesOptimization(priority));
  81669. result.addOptimization(new ShadowsOptimization(priority));
  81670. result.addOptimization(new LensFlaresOptimization(priority));
  81671. // Next priority
  81672. priority++;
  81673. result.addOptimization(new PostProcessesOptimization(priority));
  81674. result.addOptimization(new ParticlesOptimization(priority));
  81675. // Next priority
  81676. priority++;
  81677. result.addOptimization(new TextureOptimization(priority, 256));
  81678. // Next priority
  81679. priority++;
  81680. result.addOptimization(new RenderTargetsOptimization(priority));
  81681. // Next priority
  81682. priority++;
  81683. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  81684. return result;
  81685. };
  81686. return SceneOptimizerOptions;
  81687. }());
  81688. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  81689. /**
  81690. * Class used to run optimizations in order to reach a target frame rate
  81691. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81692. */
  81693. var SceneOptimizer = /** @class */ (function () {
  81694. /**
  81695. * Creates a new SceneOptimizer
  81696. * @param scene defines the scene to work on
  81697. * @param options defines the options to use with the SceneOptimizer
  81698. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  81699. * @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)
  81700. */
  81701. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  81702. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  81703. if (improvementMode === void 0) { improvementMode = false; }
  81704. var _this = this;
  81705. this._isRunning = false;
  81706. this._currentPriorityLevel = 0;
  81707. this._targetFrameRate = 60;
  81708. this._trackerDuration = 2000;
  81709. this._currentFrameRate = 0;
  81710. this._improvementMode = false;
  81711. /**
  81712. * Defines an observable called when the optimizer reaches the target frame rate
  81713. */
  81714. this.onSuccessObservable = new BABYLON.Observable();
  81715. /**
  81716. * Defines an observable called when the optimizer enables an optimization
  81717. */
  81718. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  81719. /**
  81720. * Defines an observable called when the optimizer is not able to reach the target frame rate
  81721. */
  81722. this.onFailureObservable = new BABYLON.Observable();
  81723. if (!options) {
  81724. this._options = new SceneOptimizerOptions();
  81725. }
  81726. else {
  81727. this._options = options;
  81728. }
  81729. if (this._options.targetFrameRate) {
  81730. this._targetFrameRate = this._options.targetFrameRate;
  81731. }
  81732. if (this._options.trackerDuration) {
  81733. this._trackerDuration = this._options.trackerDuration;
  81734. }
  81735. if (autoGeneratePriorities) {
  81736. var priority = 0;
  81737. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  81738. var optim = _a[_i];
  81739. optim.priority = priority++;
  81740. }
  81741. }
  81742. this._improvementMode = improvementMode;
  81743. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81744. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  81745. _this._sceneDisposeObserver = null;
  81746. _this.dispose();
  81747. });
  81748. }
  81749. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  81750. /**
  81751. * Gets a boolean indicating if the optimizer is in improvement mode
  81752. */
  81753. get: function () {
  81754. return this._improvementMode;
  81755. },
  81756. enumerable: true,
  81757. configurable: true
  81758. });
  81759. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  81760. /**
  81761. * Gets the current priority level (0 at start)
  81762. */
  81763. get: function () {
  81764. return this._currentPriorityLevel;
  81765. },
  81766. enumerable: true,
  81767. configurable: true
  81768. });
  81769. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  81770. /**
  81771. * Gets the current frame rate checked by the SceneOptimizer
  81772. */
  81773. get: function () {
  81774. return this._currentFrameRate;
  81775. },
  81776. enumerable: true,
  81777. configurable: true
  81778. });
  81779. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  81780. /**
  81781. * Gets or sets the current target frame rate (60 by default)
  81782. */
  81783. get: function () {
  81784. return this._targetFrameRate;
  81785. },
  81786. /**
  81787. * Gets or sets the current target frame rate (60 by default)
  81788. */
  81789. set: function (value) {
  81790. this._targetFrameRate = value;
  81791. },
  81792. enumerable: true,
  81793. configurable: true
  81794. });
  81795. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  81796. /**
  81797. * Gets or sets the current interval between two checks (every 2000ms by default)
  81798. */
  81799. get: function () {
  81800. return this._trackerDuration;
  81801. },
  81802. /**
  81803. * Gets or sets the current interval between two checks (every 2000ms by default)
  81804. */
  81805. set: function (value) {
  81806. this._trackerDuration = value;
  81807. },
  81808. enumerable: true,
  81809. configurable: true
  81810. });
  81811. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  81812. /**
  81813. * Gets the list of active optimizations
  81814. */
  81815. get: function () {
  81816. return this._options.optimizations;
  81817. },
  81818. enumerable: true,
  81819. configurable: true
  81820. });
  81821. /**
  81822. * Stops the current optimizer
  81823. */
  81824. SceneOptimizer.prototype.stop = function () {
  81825. this._isRunning = false;
  81826. };
  81827. /**
  81828. * Reset the optimizer to initial step (current priority level = 0)
  81829. */
  81830. SceneOptimizer.prototype.reset = function () {
  81831. this._currentPriorityLevel = 0;
  81832. };
  81833. /**
  81834. * Start the optimizer. By default it will try to reach a specific framerate
  81835. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  81836. */
  81837. SceneOptimizer.prototype.start = function () {
  81838. var _this = this;
  81839. if (this._isRunning) {
  81840. return;
  81841. }
  81842. this._isRunning = true;
  81843. // Let's wait for the scene to be ready before running our check
  81844. this._scene.executeWhenReady(function () {
  81845. setTimeout(function () {
  81846. _this._checkCurrentState();
  81847. }, _this._trackerDuration);
  81848. });
  81849. };
  81850. SceneOptimizer.prototype._checkCurrentState = function () {
  81851. var _this = this;
  81852. if (!this._isRunning) {
  81853. return;
  81854. }
  81855. var scene = this._scene;
  81856. var options = this._options;
  81857. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  81858. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  81859. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  81860. this._isRunning = false;
  81861. this.onSuccessObservable.notifyObservers(this);
  81862. return;
  81863. }
  81864. // Apply current level of optimizations
  81865. var allDone = true;
  81866. var noOptimizationApplied = true;
  81867. for (var index = 0; index < options.optimizations.length; index++) {
  81868. var optimization = options.optimizations[index];
  81869. if (optimization.priority === this._currentPriorityLevel) {
  81870. noOptimizationApplied = false;
  81871. allDone = allDone && optimization.apply(scene, this);
  81872. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  81873. }
  81874. }
  81875. // If no optimization was applied, this is a failure :(
  81876. if (noOptimizationApplied) {
  81877. this._isRunning = false;
  81878. this.onFailureObservable.notifyObservers(this);
  81879. return;
  81880. }
  81881. // If all optimizations were done, move to next level
  81882. if (allDone) {
  81883. this._currentPriorityLevel++;
  81884. }
  81885. // Let's the system running for a specific amount of time before checking FPS
  81886. scene.executeWhenReady(function () {
  81887. setTimeout(function () {
  81888. _this._checkCurrentState();
  81889. }, _this._trackerDuration);
  81890. });
  81891. };
  81892. /**
  81893. * Release all resources
  81894. */
  81895. SceneOptimizer.prototype.dispose = function () {
  81896. this.stop();
  81897. this.onSuccessObservable.clear();
  81898. this.onFailureObservable.clear();
  81899. this.onNewOptimizationAppliedObservable.clear();
  81900. if (this._sceneDisposeObserver) {
  81901. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  81902. }
  81903. };
  81904. /**
  81905. * Helper function to create a SceneOptimizer with one single line of code
  81906. * @param scene defines the scene to work on
  81907. * @param options defines the options to use with the SceneOptimizer
  81908. * @param onSuccess defines a callback to call on success
  81909. * @param onFailure defines a callback to call on failure
  81910. * @returns the new SceneOptimizer object
  81911. */
  81912. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  81913. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  81914. if (onSuccess) {
  81915. optimizer.onSuccessObservable.add(function () {
  81916. onSuccess();
  81917. });
  81918. }
  81919. if (onFailure) {
  81920. optimizer.onFailureObservable.add(function () {
  81921. onFailure();
  81922. });
  81923. }
  81924. optimizer.start();
  81925. return optimizer;
  81926. };
  81927. return SceneOptimizer;
  81928. }());
  81929. BABYLON.SceneOptimizer = SceneOptimizer;
  81930. })(BABYLON || (BABYLON = {}));
  81931. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  81932. var BABYLON;
  81933. (function (BABYLON) {
  81934. var OutlineRenderer = /** @class */ (function () {
  81935. function OutlineRenderer(scene) {
  81936. this.zOffset = 1;
  81937. this._scene = scene;
  81938. }
  81939. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  81940. var _this = this;
  81941. if (useOverlay === void 0) { useOverlay = false; }
  81942. var scene = this._scene;
  81943. var engine = this._scene.getEngine();
  81944. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  81945. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  81946. return;
  81947. }
  81948. var mesh = subMesh.getRenderingMesh();
  81949. var material = subMesh.getMaterial();
  81950. if (!material || !scene.activeCamera) {
  81951. return;
  81952. }
  81953. engine.enableEffect(this._effect);
  81954. // Logarithmic depth
  81955. if (material.useLogarithmicDepth) {
  81956. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  81957. }
  81958. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  81959. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  81960. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  81961. // Bones
  81962. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81963. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81964. }
  81965. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  81966. // Alpha test
  81967. if (material && material.needAlphaTesting()) {
  81968. var alphaTexture = material.getAlphaTestTexture();
  81969. if (alphaTexture) {
  81970. this._effect.setTexture("diffuseSampler", alphaTexture);
  81971. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81972. }
  81973. }
  81974. engine.setZOffset(-this.zOffset);
  81975. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  81976. engine.setZOffset(0);
  81977. };
  81978. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  81979. var defines = [];
  81980. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81981. var mesh = subMesh.getMesh();
  81982. var material = subMesh.getMaterial();
  81983. if (material) {
  81984. // Alpha test
  81985. if (material.needAlphaTesting()) {
  81986. defines.push("#define ALPHATEST");
  81987. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81988. attribs.push(BABYLON.VertexBuffer.UVKind);
  81989. defines.push("#define UV1");
  81990. }
  81991. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81992. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81993. defines.push("#define UV2");
  81994. }
  81995. }
  81996. //Logarithmic depth
  81997. if (material.useLogarithmicDepth) {
  81998. defines.push("#define LOGARITHMICDEPTH");
  81999. }
  82000. }
  82001. // Bones
  82002. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82003. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82004. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82005. if (mesh.numBoneInfluencers > 4) {
  82006. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82007. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82008. }
  82009. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82010. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  82011. }
  82012. else {
  82013. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82014. }
  82015. // Instances
  82016. if (useInstances) {
  82017. defines.push("#define INSTANCES");
  82018. attribs.push("world0");
  82019. attribs.push("world1");
  82020. attribs.push("world2");
  82021. attribs.push("world3");
  82022. }
  82023. // Get correct effect
  82024. var join = defines.join("\n");
  82025. if (this._cachedDefines !== join) {
  82026. this._cachedDefines = join;
  82027. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  82028. }
  82029. return this._effect.isReady();
  82030. };
  82031. return OutlineRenderer;
  82032. }());
  82033. BABYLON.OutlineRenderer = OutlineRenderer;
  82034. })(BABYLON || (BABYLON = {}));
  82035. //# sourceMappingURL=babylon.outlineRenderer.js.map
  82036. var BABYLON;
  82037. (function (BABYLON) {
  82038. var FaceAdjacencies = /** @class */ (function () {
  82039. function FaceAdjacencies() {
  82040. this.edges = new Array();
  82041. this.edgesConnectedCount = 0;
  82042. }
  82043. return FaceAdjacencies;
  82044. }());
  82045. var EdgesRenderer = /** @class */ (function () {
  82046. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  82047. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  82048. if (epsilon === void 0) { epsilon = 0.95; }
  82049. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  82050. this.edgesWidthScalerForOrthographic = 1000.0;
  82051. this.edgesWidthScalerForPerspective = 50.0;
  82052. this._linesPositions = new Array();
  82053. this._linesNormals = new Array();
  82054. this._linesIndices = new Array();
  82055. this._buffers = {};
  82056. this._checkVerticesInsteadOfIndices = false;
  82057. this._source = source;
  82058. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  82059. this._epsilon = epsilon;
  82060. this._prepareRessources();
  82061. this._generateEdgesLines();
  82062. }
  82063. EdgesRenderer.prototype._prepareRessources = function () {
  82064. if (this._lineShader) {
  82065. return;
  82066. }
  82067. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  82068. attributes: ["position", "normal"],
  82069. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  82070. });
  82071. this._lineShader.disableDepthWrite = true;
  82072. this._lineShader.backFaceCulling = false;
  82073. };
  82074. EdgesRenderer.prototype._rebuild = function () {
  82075. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  82076. if (buffer) {
  82077. buffer._rebuild();
  82078. }
  82079. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  82080. if (buffer) {
  82081. buffer._rebuild();
  82082. }
  82083. var scene = this._source.getScene();
  82084. var engine = scene.getEngine();
  82085. this._ib = engine.createIndexBuffer(this._linesIndices);
  82086. };
  82087. EdgesRenderer.prototype.dispose = function () {
  82088. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  82089. if (buffer) {
  82090. buffer.dispose();
  82091. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  82092. }
  82093. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  82094. if (buffer) {
  82095. buffer.dispose();
  82096. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  82097. }
  82098. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  82099. this._lineShader.dispose();
  82100. };
  82101. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  82102. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  82103. return 0;
  82104. }
  82105. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  82106. return 1;
  82107. }
  82108. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  82109. return 2;
  82110. }
  82111. return -1;
  82112. };
  82113. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  82114. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  82115. return 0;
  82116. }
  82117. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  82118. return 1;
  82119. }
  82120. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  82121. return 2;
  82122. }
  82123. return -1;
  82124. };
  82125. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  82126. var needToCreateLine;
  82127. if (edge === undefined) {
  82128. needToCreateLine = true;
  82129. }
  82130. else {
  82131. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  82132. needToCreateLine = dotProduct < this._epsilon;
  82133. }
  82134. if (needToCreateLine) {
  82135. var offset = this._linesPositions.length / 3;
  82136. var normal = p0.subtract(p1);
  82137. normal.normalize();
  82138. // Positions
  82139. this._linesPositions.push(p0.x);
  82140. this._linesPositions.push(p0.y);
  82141. this._linesPositions.push(p0.z);
  82142. this._linesPositions.push(p0.x);
  82143. this._linesPositions.push(p0.y);
  82144. this._linesPositions.push(p0.z);
  82145. this._linesPositions.push(p1.x);
  82146. this._linesPositions.push(p1.y);
  82147. this._linesPositions.push(p1.z);
  82148. this._linesPositions.push(p1.x);
  82149. this._linesPositions.push(p1.y);
  82150. this._linesPositions.push(p1.z);
  82151. // Normals
  82152. this._linesNormals.push(p1.x);
  82153. this._linesNormals.push(p1.y);
  82154. this._linesNormals.push(p1.z);
  82155. this._linesNormals.push(-1);
  82156. this._linesNormals.push(p1.x);
  82157. this._linesNormals.push(p1.y);
  82158. this._linesNormals.push(p1.z);
  82159. this._linesNormals.push(1);
  82160. this._linesNormals.push(p0.x);
  82161. this._linesNormals.push(p0.y);
  82162. this._linesNormals.push(p0.z);
  82163. this._linesNormals.push(-1);
  82164. this._linesNormals.push(p0.x);
  82165. this._linesNormals.push(p0.y);
  82166. this._linesNormals.push(p0.z);
  82167. this._linesNormals.push(1);
  82168. // Indices
  82169. this._linesIndices.push(offset);
  82170. this._linesIndices.push(offset + 1);
  82171. this._linesIndices.push(offset + 2);
  82172. this._linesIndices.push(offset);
  82173. this._linesIndices.push(offset + 2);
  82174. this._linesIndices.push(offset + 3);
  82175. }
  82176. };
  82177. EdgesRenderer.prototype._generateEdgesLines = function () {
  82178. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82179. var indices = this._source.getIndices();
  82180. if (!indices || !positions) {
  82181. return;
  82182. }
  82183. // First let's find adjacencies
  82184. var adjacencies = new Array();
  82185. var faceNormals = new Array();
  82186. var index;
  82187. var faceAdjacencies;
  82188. // Prepare faces
  82189. for (index = 0; index < indices.length; index += 3) {
  82190. faceAdjacencies = new FaceAdjacencies();
  82191. var p0Index = indices[index];
  82192. var p1Index = indices[index + 1];
  82193. var p2Index = indices[index + 2];
  82194. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  82195. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  82196. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  82197. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  82198. faceNormal.normalize();
  82199. faceNormals.push(faceNormal);
  82200. adjacencies.push(faceAdjacencies);
  82201. }
  82202. // Scan
  82203. for (index = 0; index < adjacencies.length; index++) {
  82204. faceAdjacencies = adjacencies[index];
  82205. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  82206. var otherFaceAdjacencies = adjacencies[otherIndex];
  82207. if (faceAdjacencies.edgesConnectedCount === 3) {
  82208. break;
  82209. }
  82210. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  82211. continue;
  82212. }
  82213. var otherP0 = indices[otherIndex * 3];
  82214. var otherP1 = indices[otherIndex * 3 + 1];
  82215. var otherP2 = indices[otherIndex * 3 + 2];
  82216. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  82217. var otherEdgeIndex = 0;
  82218. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  82219. continue;
  82220. }
  82221. switch (edgeIndex) {
  82222. case 0:
  82223. if (this._checkVerticesInsteadOfIndices) {
  82224. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82225. }
  82226. else {
  82227. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  82228. }
  82229. break;
  82230. case 1:
  82231. if (this._checkVerticesInsteadOfIndices) {
  82232. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82233. }
  82234. else {
  82235. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  82236. }
  82237. break;
  82238. case 2:
  82239. if (this._checkVerticesInsteadOfIndices) {
  82240. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82241. }
  82242. else {
  82243. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  82244. }
  82245. break;
  82246. }
  82247. if (otherEdgeIndex === -1) {
  82248. continue;
  82249. }
  82250. faceAdjacencies.edges[edgeIndex] = otherIndex;
  82251. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  82252. faceAdjacencies.edgesConnectedCount++;
  82253. otherFaceAdjacencies.edgesConnectedCount++;
  82254. if (faceAdjacencies.edgesConnectedCount === 3) {
  82255. break;
  82256. }
  82257. }
  82258. }
  82259. }
  82260. // Create lines
  82261. for (index = 0; index < adjacencies.length; index++) {
  82262. // 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
  82263. var current = adjacencies[index];
  82264. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  82265. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  82266. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  82267. }
  82268. // Merge into a single mesh
  82269. var engine = this._source.getScene().getEngine();
  82270. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  82271. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  82272. this._ib = engine.createIndexBuffer(this._linesIndices);
  82273. this._indicesCount = this._linesIndices.length;
  82274. };
  82275. EdgesRenderer.prototype.render = function () {
  82276. var scene = this._source.getScene();
  82277. if (!this._lineShader.isReady() || !scene.activeCamera) {
  82278. return;
  82279. }
  82280. var engine = scene.getEngine();
  82281. this._lineShader._preBind();
  82282. // VBOs
  82283. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  82284. scene.resetCachedMaterial();
  82285. this._lineShader.setColor4("color", this._source.edgesColor);
  82286. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  82287. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  82288. }
  82289. else {
  82290. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  82291. }
  82292. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  82293. this._lineShader.bind(this._source.getWorldMatrix());
  82294. // Draw order
  82295. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  82296. this._lineShader.unbind();
  82297. engine.setDepthWrite(true);
  82298. };
  82299. return EdgesRenderer;
  82300. }());
  82301. BABYLON.EdgesRenderer = EdgesRenderer;
  82302. })(BABYLON || (BABYLON = {}));
  82303. //# sourceMappingURL=babylon.edgesRenderer.js.map
  82304. var __assign = (this && this.__assign) || Object.assign || function(t) {
  82305. for (var s, i = 1, n = arguments.length; i < n; i++) {
  82306. s = arguments[i];
  82307. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  82308. t[p] = s[p];
  82309. }
  82310. return t;
  82311. };
  82312. var BABYLON;
  82313. (function (BABYLON) {
  82314. /**
  82315. * The effect layer Helps adding post process effect blended with the main pass.
  82316. *
  82317. * This can be for instance use to generate glow or higlight effects on the scene.
  82318. *
  82319. * The effect layer class can not be used directly and is intented to inherited from to be
  82320. * customized per effects.
  82321. */
  82322. var EffectLayer = /** @class */ (function () {
  82323. /**
  82324. * Instantiates a new effect Layer and references it in the scene.
  82325. * @param name The name of the layer
  82326. * @param scene The scene to use the layer in
  82327. */
  82328. function EffectLayer(
  82329. /** The Friendly of the effect in the scene */
  82330. name, scene) {
  82331. this.name = name;
  82332. this._vertexBuffers = {};
  82333. this._maxSize = 0;
  82334. this._mainTextureDesiredSize = { width: 0, height: 0 };
  82335. this._shouldRender = true;
  82336. this._postProcesses = [];
  82337. this._textures = [];
  82338. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  82339. /**
  82340. * The clear color of the texture used to generate the glow map.
  82341. */
  82342. this.neutralColor = new BABYLON.Color4();
  82343. /**
  82344. * Specifies wether the highlight layer is enabled or not.
  82345. */
  82346. this.isEnabled = true;
  82347. /**
  82348. * An event triggered when the effect layer has been disposed.
  82349. */
  82350. this.onDisposeObservable = new BABYLON.Observable();
  82351. /**
  82352. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  82353. */
  82354. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  82355. /**
  82356. * An event triggered when the generated texture is being merged in the scene.
  82357. */
  82358. this.onBeforeComposeObservable = new BABYLON.Observable();
  82359. /**
  82360. * An event triggered when the generated texture has been merged in the scene.
  82361. */
  82362. this.onAfterComposeObservable = new BABYLON.Observable();
  82363. /**
  82364. * An event triggered when the efffect layer changes its size.
  82365. */
  82366. this.onSizeChangedObservable = new BABYLON.Observable();
  82367. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82368. this._engine = scene.getEngine();
  82369. this._maxSize = this._engine.getCaps().maxTextureSize;
  82370. this._scene.effectLayers.push(this);
  82371. // Generate Buffers
  82372. this._generateIndexBuffer();
  82373. this._genrateVertexBuffer();
  82374. }
  82375. Object.defineProperty(EffectLayer.prototype, "camera", {
  82376. /**
  82377. * Gets the camera attached to the layer.
  82378. */
  82379. get: function () {
  82380. return this._effectLayerOptions.camera;
  82381. },
  82382. enumerable: true,
  82383. configurable: true
  82384. });
  82385. /**
  82386. * Initializes the effect layer with the required options.
  82387. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  82388. */
  82389. EffectLayer.prototype._init = function (options) {
  82390. // Adapt options
  82391. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82392. this._setMainTextureSize();
  82393. this._createMainTexture();
  82394. this._createTextureAndPostProcesses();
  82395. this._mergeEffect = this._createMergeEffect();
  82396. };
  82397. /**
  82398. * Generates the index buffer of the full screen quad blending to the main canvas.
  82399. */
  82400. EffectLayer.prototype._generateIndexBuffer = function () {
  82401. // Indices
  82402. var indices = [];
  82403. indices.push(0);
  82404. indices.push(1);
  82405. indices.push(2);
  82406. indices.push(0);
  82407. indices.push(2);
  82408. indices.push(3);
  82409. this._indexBuffer = this._engine.createIndexBuffer(indices);
  82410. };
  82411. /**
  82412. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  82413. */
  82414. EffectLayer.prototype._genrateVertexBuffer = function () {
  82415. // VBO
  82416. var vertices = [];
  82417. vertices.push(1, 1);
  82418. vertices.push(-1, 1);
  82419. vertices.push(-1, -1);
  82420. vertices.push(1, -1);
  82421. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82422. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  82423. };
  82424. /**
  82425. * Sets the main texture desired size which is the closest power of two
  82426. * of the engine canvas size.
  82427. */
  82428. EffectLayer.prototype._setMainTextureSize = function () {
  82429. if (this._effectLayerOptions.mainTextureFixedSize) {
  82430. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  82431. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  82432. }
  82433. else {
  82434. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  82435. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  82436. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  82437. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  82438. }
  82439. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  82440. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  82441. };
  82442. /**
  82443. * Creates the main texture for the effect layer.
  82444. */
  82445. EffectLayer.prototype._createMainTexture = function () {
  82446. var _this = this;
  82447. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  82448. width: this._mainTextureDesiredSize.width,
  82449. height: this._mainTextureDesiredSize.height
  82450. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82451. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  82452. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82453. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82454. this._mainTexture.anisotropicFilteringLevel = 1;
  82455. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82456. this._mainTexture.renderParticles = false;
  82457. this._mainTexture.renderList = null;
  82458. this._mainTexture.ignoreCameraViewport = true;
  82459. // Custom render function
  82460. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82461. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  82462. var index;
  82463. var engine = _this._scene.getEngine();
  82464. if (depthOnlySubMeshes.length) {
  82465. engine.setColorWrite(false);
  82466. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82467. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  82468. }
  82469. engine.setColorWrite(true);
  82470. }
  82471. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82472. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  82473. }
  82474. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82475. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  82476. }
  82477. for (index = 0; index < transparentSubMeshes.length; index++) {
  82478. _this._renderSubMesh(transparentSubMeshes.data[index]);
  82479. }
  82480. };
  82481. this._mainTexture.onClearObservable.add(function (engine) {
  82482. engine.clear(_this.neutralColor, true, true, true);
  82483. });
  82484. };
  82485. /**
  82486. * Checks for the readiness of the element composing the layer.
  82487. * @param subMesh the mesh to check for
  82488. * @param useInstances specify wether or not to use instances to render the mesh
  82489. * @param emissiveTexture the associated emissive texture used to generate the glow
  82490. * @return true if ready otherwise, false
  82491. */
  82492. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  82493. var material = subMesh.getMaterial();
  82494. if (!material) {
  82495. return false;
  82496. }
  82497. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  82498. return false;
  82499. }
  82500. var defines = [];
  82501. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82502. var mesh = subMesh.getMesh();
  82503. var uv1 = false;
  82504. var uv2 = false;
  82505. // Alpha test
  82506. if (material && material.needAlphaTesting()) {
  82507. var alphaTexture = material.getAlphaTestTexture();
  82508. if (alphaTexture) {
  82509. defines.push("#define ALPHATEST");
  82510. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82511. alphaTexture.coordinatesIndex === 1) {
  82512. defines.push("#define DIFFUSEUV2");
  82513. uv2 = true;
  82514. }
  82515. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82516. defines.push("#define DIFFUSEUV1");
  82517. uv1 = true;
  82518. }
  82519. }
  82520. }
  82521. // Emissive
  82522. if (emissiveTexture) {
  82523. defines.push("#define EMISSIVE");
  82524. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82525. emissiveTexture.coordinatesIndex === 1) {
  82526. defines.push("#define EMISSIVEUV2");
  82527. uv2 = true;
  82528. }
  82529. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82530. defines.push("#define EMISSIVEUV1");
  82531. uv1 = true;
  82532. }
  82533. }
  82534. if (uv1) {
  82535. attribs.push(BABYLON.VertexBuffer.UVKind);
  82536. defines.push("#define UV1");
  82537. }
  82538. if (uv2) {
  82539. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82540. defines.push("#define UV2");
  82541. }
  82542. // Bones
  82543. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82544. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82545. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82546. if (mesh.numBoneInfluencers > 4) {
  82547. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82548. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82549. }
  82550. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82551. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  82552. }
  82553. else {
  82554. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82555. }
  82556. // Instances
  82557. if (useInstances) {
  82558. defines.push("#define INSTANCES");
  82559. attribs.push("world0");
  82560. attribs.push("world1");
  82561. attribs.push("world2");
  82562. attribs.push("world3");
  82563. }
  82564. // Get correct effect
  82565. var join = defines.join("\n");
  82566. if (this._cachedDefines !== join) {
  82567. this._cachedDefines = join;
  82568. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  82569. }
  82570. return this._effectLayerMapGenerationEffect.isReady();
  82571. };
  82572. /**
  82573. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  82574. */
  82575. EffectLayer.prototype.render = function () {
  82576. var currentEffect = this._mergeEffect;
  82577. // Check
  82578. if (!currentEffect.isReady())
  82579. return;
  82580. for (var i = 0; i < this._postProcesses.length; i++) {
  82581. if (!this._postProcesses[i].isReady()) {
  82582. return;
  82583. }
  82584. }
  82585. var engine = this._scene.getEngine();
  82586. this.onBeforeComposeObservable.notifyObservers(this);
  82587. // Render
  82588. engine.enableEffect(currentEffect);
  82589. engine.setState(false);
  82590. // VBOs
  82591. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82592. // Cache
  82593. var previousAlphaMode = engine.getAlphaMode();
  82594. // Go Blend.
  82595. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  82596. // Blends the map on the main canvas.
  82597. this._internalRender(currentEffect);
  82598. // Restore Alpha
  82599. engine.setAlphaMode(previousAlphaMode);
  82600. this.onAfterComposeObservable.notifyObservers(this);
  82601. // Handle size changes.
  82602. var size = this._mainTexture.getSize();
  82603. this._setMainTextureSize();
  82604. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  82605. // Recreate RTT and post processes on size change.
  82606. this.onSizeChangedObservable.notifyObservers(this);
  82607. this._disposeTextureAndPostProcesses();
  82608. this._createMainTexture();
  82609. this._createTextureAndPostProcesses();
  82610. }
  82611. };
  82612. /**
  82613. * Determine if a given mesh will be used in the current effect.
  82614. * @param mesh mesh to test
  82615. * @returns true if the mesh will be used
  82616. */
  82617. EffectLayer.prototype.hasMesh = function (mesh) {
  82618. return true;
  82619. };
  82620. /**
  82621. * Returns true if the layer contains information to display, otherwise false.
  82622. * @returns true if the glow layer should be rendered
  82623. */
  82624. EffectLayer.prototype.shouldRender = function () {
  82625. return this.isEnabled && this._shouldRender;
  82626. };
  82627. /**
  82628. * Returns true if the mesh should render, otherwise false.
  82629. * @param mesh The mesh to render
  82630. * @returns true if it should render otherwise false
  82631. */
  82632. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  82633. return true;
  82634. };
  82635. /**
  82636. * Returns true if the mesh should render, otherwise false.
  82637. * @param mesh The mesh to render
  82638. * @returns true if it should render otherwise false
  82639. */
  82640. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  82641. return true;
  82642. };
  82643. /**
  82644. * Renders the submesh passed in parameter to the generation map.
  82645. */
  82646. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  82647. var _this = this;
  82648. if (!this.shouldRender()) {
  82649. return;
  82650. }
  82651. var material = subMesh.getMaterial();
  82652. var mesh = subMesh.getRenderingMesh();
  82653. var scene = this._scene;
  82654. var engine = scene.getEngine();
  82655. if (!material) {
  82656. return;
  82657. }
  82658. // Do not block in blend mode.
  82659. if (material.needAlphaBlendingForMesh(mesh)) {
  82660. return;
  82661. }
  82662. // Culling
  82663. engine.setState(material.backFaceCulling);
  82664. // Managing instances
  82665. var batch = mesh._getInstancesRenderList(subMesh._id);
  82666. if (batch.mustReturn) {
  82667. return;
  82668. }
  82669. // Early Exit per mesh
  82670. if (!this._shouldRenderMesh(mesh)) {
  82671. return;
  82672. }
  82673. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82674. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  82675. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  82676. engine.enableEffect(this._effectLayerMapGenerationEffect);
  82677. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  82678. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  82679. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  82680. // Alpha test
  82681. if (material && material.needAlphaTesting()) {
  82682. var alphaTexture = material.getAlphaTestTexture();
  82683. if (alphaTexture) {
  82684. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  82685. var textureMatrix = alphaTexture.getTextureMatrix();
  82686. if (textureMatrix) {
  82687. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  82688. }
  82689. }
  82690. }
  82691. // Glow emissive only
  82692. if (this._emissiveTextureAndColor.texture) {
  82693. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  82694. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  82695. }
  82696. // Bones
  82697. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82698. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82699. }
  82700. // Draw
  82701. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  82702. }
  82703. else {
  82704. // Need to reset refresh rate of the shadowMap
  82705. this._mainTexture.resetRefreshCounter();
  82706. }
  82707. };
  82708. /**
  82709. * Rebuild the required buffers.
  82710. * @ignore Internal use only.
  82711. */
  82712. EffectLayer.prototype._rebuild = function () {
  82713. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82714. if (vb) {
  82715. vb._rebuild();
  82716. }
  82717. this._generateIndexBuffer();
  82718. };
  82719. /**
  82720. * Dispose only the render target textures and post process.
  82721. */
  82722. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  82723. this._mainTexture.dispose();
  82724. for (var i = 0; i < this._postProcesses.length; i++) {
  82725. if (this._postProcesses[i]) {
  82726. this._postProcesses[i].dispose();
  82727. }
  82728. }
  82729. this._postProcesses = [];
  82730. for (var i = 0; i < this._textures.length; i++) {
  82731. if (this._textures[i]) {
  82732. this._textures[i].dispose();
  82733. }
  82734. }
  82735. this._textures = [];
  82736. };
  82737. /**
  82738. * Dispose the highlight layer and free resources.
  82739. */
  82740. EffectLayer.prototype.dispose = function () {
  82741. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82742. if (vertexBuffer) {
  82743. vertexBuffer.dispose();
  82744. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82745. }
  82746. if (this._indexBuffer) {
  82747. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82748. this._indexBuffer = null;
  82749. }
  82750. // Clean textures and post processes
  82751. this._disposeTextureAndPostProcesses();
  82752. // Remove from scene
  82753. var index = this._scene.effectLayers.indexOf(this, 0);
  82754. if (index > -1) {
  82755. this._scene.effectLayers.splice(index, 1);
  82756. }
  82757. // Callback
  82758. this.onDisposeObservable.notifyObservers(this);
  82759. this.onDisposeObservable.clear();
  82760. this.onBeforeRenderMainTextureObservable.clear();
  82761. this.onBeforeComposeObservable.clear();
  82762. this.onAfterComposeObservable.clear();
  82763. this.onSizeChangedObservable.clear();
  82764. };
  82765. return EffectLayer;
  82766. }());
  82767. BABYLON.EffectLayer = EffectLayer;
  82768. })(BABYLON || (BABYLON = {}));
  82769. //# sourceMappingURL=babylon.effectLayer.js.map
  82770. var __assign = (this && this.__assign) || Object.assign || function(t) {
  82771. for (var s, i = 1, n = arguments.length; i < n; i++) {
  82772. s = arguments[i];
  82773. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  82774. t[p] = s[p];
  82775. }
  82776. return t;
  82777. };
  82778. var BABYLON;
  82779. (function (BABYLON) {
  82780. /**
  82781. * Special Glow Blur post process only blurring the alpha channel
  82782. * It enforces keeping the most luminous color in the color channel.
  82783. */
  82784. var GlowBlurPostProcess = /** @class */ (function (_super) {
  82785. __extends(GlowBlurPostProcess, _super);
  82786. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  82787. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82788. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  82789. _this.direction = direction;
  82790. _this.kernel = kernel;
  82791. _this.onApplyObservable.add(function (effect) {
  82792. effect.setFloat2("screenSize", _this.width, _this.height);
  82793. effect.setVector2("direction", _this.direction);
  82794. effect.setFloat("blurWidth", _this.kernel);
  82795. });
  82796. return _this;
  82797. }
  82798. return GlowBlurPostProcess;
  82799. }(BABYLON.PostProcess));
  82800. /**
  82801. * The highlight layer Helps adding a glow effect around a mesh.
  82802. *
  82803. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  82804. * glowy meshes to your scene.
  82805. *
  82806. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  82807. */
  82808. var HighlightLayer = /** @class */ (function (_super) {
  82809. __extends(HighlightLayer, _super);
  82810. /**
  82811. * Instantiates a new highlight Layer and references it to the scene..
  82812. * @param name The name of the layer
  82813. * @param scene The scene to use the layer in
  82814. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  82815. */
  82816. function HighlightLayer(name, scene, options) {
  82817. var _this = _super.call(this, name, scene) || this;
  82818. _this.name = name;
  82819. /**
  82820. * Specifies whether or not the inner glow is ACTIVE in the layer.
  82821. */
  82822. _this.innerGlow = true;
  82823. /**
  82824. * Specifies whether or not the outer glow is ACTIVE in the layer.
  82825. */
  82826. _this.outerGlow = true;
  82827. /**
  82828. * An event triggered when the highlight layer is being blurred.
  82829. */
  82830. _this.onBeforeBlurObservable = new BABYLON.Observable();
  82831. /**
  82832. * An event triggered when the highlight layer has been blurred.
  82833. */
  82834. _this.onAfterBlurObservable = new BABYLON.Observable();
  82835. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  82836. _this._meshes = {};
  82837. _this._excludedMeshes = {};
  82838. _this.neutralColor = HighlightLayer.NeutralColor;
  82839. // Warn on stencil
  82840. if (!_this._engine.isStencilEnable) {
  82841. 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 }");
  82842. }
  82843. // Adapt options
  82844. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82845. // Initialize the layer
  82846. _this._init({
  82847. alphaBlendingMode: _this._options.alphaBlendingMode,
  82848. camera: _this._options.camera,
  82849. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  82850. mainTextureRatio: _this._options.mainTextureRatio
  82851. });
  82852. return _this;
  82853. }
  82854. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  82855. /**
  82856. * Gets the horizontal size of the blur.
  82857. */
  82858. get: function () {
  82859. return this._horizontalBlurPostprocess.kernel;
  82860. },
  82861. /**
  82862. * Specifies the horizontal size of the blur.
  82863. */
  82864. set: function (value) {
  82865. this._horizontalBlurPostprocess.kernel = value;
  82866. },
  82867. enumerable: true,
  82868. configurable: true
  82869. });
  82870. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  82871. /**
  82872. * Gets the vertical size of the blur.
  82873. */
  82874. get: function () {
  82875. return this._verticalBlurPostprocess.kernel;
  82876. },
  82877. /**
  82878. * Specifies the vertical size of the blur.
  82879. */
  82880. set: function (value) {
  82881. this._verticalBlurPostprocess.kernel = value;
  82882. },
  82883. enumerable: true,
  82884. configurable: true
  82885. });
  82886. /**
  82887. * Get the effect name of the layer.
  82888. * @return The effect name
  82889. */
  82890. HighlightLayer.prototype.getEffectName = function () {
  82891. return HighlightLayer.EffectName;
  82892. };
  82893. /**
  82894. * Create the merge effect. This is the shader use to blit the information back
  82895. * to the main canvas at the end of the scene rendering.
  82896. */
  82897. HighlightLayer.prototype._createMergeEffect = function () {
  82898. // Effect
  82899. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  82900. };
  82901. /**
  82902. * Creates the render target textures and post processes used in the highlight layer.
  82903. */
  82904. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  82905. var _this = this;
  82906. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  82907. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  82908. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  82909. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  82910. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  82911. width: blurTextureWidth,
  82912. height: blurTextureHeight
  82913. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82914. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82915. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82916. this._blurTexture.anisotropicFilteringLevel = 16;
  82917. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82918. this._blurTexture.renderParticles = false;
  82919. this._blurTexture.ignoreCameraViewport = true;
  82920. this._textures = [this._blurTexture];
  82921. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  82922. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82923. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  82924. effect.setTexture("textureSampler", _this._mainTexture);
  82925. });
  82926. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82927. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  82928. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  82929. });
  82930. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82931. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  82932. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  82933. });
  82934. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  82935. }
  82936. else {
  82937. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  82938. width: blurTextureWidth,
  82939. height: blurTextureHeight
  82940. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82941. this._horizontalBlurPostprocess.width = blurTextureWidth;
  82942. this._horizontalBlurPostprocess.height = blurTextureHeight;
  82943. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  82944. effect.setTexture("textureSampler", _this._mainTexture);
  82945. });
  82946. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  82947. width: blurTextureWidth,
  82948. height: blurTextureHeight
  82949. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82950. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  82951. }
  82952. this._mainTexture.onAfterUnbindObservable.add(function () {
  82953. _this.onBeforeBlurObservable.notifyObservers(_this);
  82954. var internalTexture = _this._blurTexture.getInternalTexture();
  82955. if (internalTexture) {
  82956. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  82957. }
  82958. _this.onAfterBlurObservable.notifyObservers(_this);
  82959. });
  82960. // Prevent autoClear.
  82961. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  82962. };
  82963. /**
  82964. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  82965. */
  82966. HighlightLayer.prototype.needStencil = function () {
  82967. return true;
  82968. };
  82969. /**
  82970. * Checks for the readiness of the element composing the layer.
  82971. * @param subMesh the mesh to check for
  82972. * @param useInstances specify wether or not to use instances to render the mesh
  82973. * @param emissiveTexture the associated emissive texture used to generate the glow
  82974. * @return true if ready otherwise, false
  82975. */
  82976. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  82977. var material = subMesh.getMaterial();
  82978. var mesh = subMesh.getRenderingMesh();
  82979. if (!material || !mesh || !this._meshes) {
  82980. return false;
  82981. }
  82982. var emissiveTexture = null;
  82983. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  82984. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  82985. emissiveTexture = material.emissiveTexture;
  82986. }
  82987. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  82988. };
  82989. /**
  82990. * Implementation specific of rendering the generating effect on the main canvas.
  82991. * @param effect The effect used to render through
  82992. */
  82993. HighlightLayer.prototype._internalRender = function (effect) {
  82994. // Texture
  82995. effect.setTexture("textureSampler", this._blurTexture);
  82996. // Cache
  82997. var engine = this._engine;
  82998. var previousStencilBuffer = engine.getStencilBuffer();
  82999. var previousStencilFunction = engine.getStencilFunction();
  83000. var previousStencilMask = engine.getStencilMask();
  83001. var previousStencilOperationPass = engine.getStencilOperationPass();
  83002. var previousStencilOperationFail = engine.getStencilOperationFail();
  83003. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  83004. // Stencil operations
  83005. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  83006. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  83007. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  83008. // Draw order
  83009. engine.setStencilMask(0x00);
  83010. engine.setStencilBuffer(true);
  83011. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  83012. // 2 passes inner outer
  83013. if (this.outerGlow) {
  83014. effect.setFloat("offset", 0);
  83015. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  83016. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83017. }
  83018. if (this.innerGlow) {
  83019. effect.setFloat("offset", 1);
  83020. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  83021. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83022. }
  83023. // Restore Cache
  83024. engine.setStencilFunction(previousStencilFunction);
  83025. engine.setStencilMask(previousStencilMask);
  83026. engine.setStencilBuffer(previousStencilBuffer);
  83027. engine.setStencilOperationPass(previousStencilOperationPass);
  83028. engine.setStencilOperationFail(previousStencilOperationFail);
  83029. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  83030. };
  83031. /**
  83032. * Returns true if the layer contains information to display, otherwise false.
  83033. */
  83034. HighlightLayer.prototype.shouldRender = function () {
  83035. if (_super.prototype.shouldRender.call(this)) {
  83036. return this._meshes ? true : false;
  83037. }
  83038. return false;
  83039. };
  83040. /**
  83041. * Returns true if the mesh should render, otherwise false.
  83042. * @param mesh The mesh to render
  83043. * @returns true if it should render otherwise false
  83044. */
  83045. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  83046. // Excluded Mesh
  83047. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  83048. return false;
  83049. }
  83050. ;
  83051. return true;
  83052. };
  83053. /**
  83054. * Sets the required values for both the emissive texture and and the main color.
  83055. */
  83056. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83057. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  83058. if (highlightLayerMesh) {
  83059. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  83060. }
  83061. else {
  83062. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83063. }
  83064. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  83065. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83066. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  83067. }
  83068. else {
  83069. this._emissiveTextureAndColor.texture = null;
  83070. }
  83071. };
  83072. /**
  83073. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  83074. * @param mesh The mesh to exclude from the highlight layer
  83075. */
  83076. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  83077. if (!this._excludedMeshes) {
  83078. return;
  83079. }
  83080. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  83081. if (!meshExcluded) {
  83082. this._excludedMeshes[mesh.uniqueId] = {
  83083. mesh: mesh,
  83084. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  83085. mesh.getEngine().setStencilBuffer(false);
  83086. }),
  83087. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  83088. mesh.getEngine().setStencilBuffer(true);
  83089. }),
  83090. };
  83091. }
  83092. };
  83093. /**
  83094. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  83095. * @param mesh The mesh to highlight
  83096. */
  83097. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  83098. if (!this._excludedMeshes) {
  83099. return;
  83100. }
  83101. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  83102. if (meshExcluded) {
  83103. if (meshExcluded.beforeRender) {
  83104. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  83105. }
  83106. if (meshExcluded.afterRender) {
  83107. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  83108. }
  83109. }
  83110. this._excludedMeshes[mesh.uniqueId] = null;
  83111. };
  83112. /**
  83113. * Determine if a given mesh will be highlighted by the current HighlightLayer
  83114. * @param mesh mesh to test
  83115. * @returns true if the mesh will be highlighted by the current HighlightLayer
  83116. */
  83117. HighlightLayer.prototype.hasMesh = function (mesh) {
  83118. if (!this._meshes) {
  83119. return false;
  83120. }
  83121. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  83122. };
  83123. /**
  83124. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  83125. * @param mesh The mesh to highlight
  83126. * @param color The color of the highlight
  83127. * @param glowEmissiveOnly Extract the glow from the emissive texture
  83128. */
  83129. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  83130. var _this = this;
  83131. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  83132. if (!this._meshes) {
  83133. return;
  83134. }
  83135. var meshHighlight = this._meshes[mesh.uniqueId];
  83136. if (meshHighlight) {
  83137. meshHighlight.color = color;
  83138. }
  83139. else {
  83140. this._meshes[mesh.uniqueId] = {
  83141. mesh: mesh,
  83142. color: color,
  83143. // Lambda required for capture due to Observable this context
  83144. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  83145. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  83146. _this._defaultStencilReference(mesh);
  83147. }
  83148. else {
  83149. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  83150. }
  83151. }),
  83152. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  83153. glowEmissiveOnly: glowEmissiveOnly
  83154. };
  83155. }
  83156. this._shouldRender = true;
  83157. };
  83158. /**
  83159. * Remove a mesh from the highlight layer in order to make it stop glowing.
  83160. * @param mesh The mesh to highlight
  83161. */
  83162. HighlightLayer.prototype.removeMesh = function (mesh) {
  83163. if (!this._meshes) {
  83164. return;
  83165. }
  83166. var meshHighlight = this._meshes[mesh.uniqueId];
  83167. if (meshHighlight) {
  83168. if (meshHighlight.observerHighlight) {
  83169. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83170. }
  83171. if (meshHighlight.observerDefault) {
  83172. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83173. }
  83174. delete this._meshes[mesh.uniqueId];
  83175. }
  83176. this._shouldRender = false;
  83177. for (var meshHighlightToCheck in this._meshes) {
  83178. if (this._meshes[meshHighlightToCheck]) {
  83179. this._shouldRender = true;
  83180. break;
  83181. }
  83182. }
  83183. };
  83184. /**
  83185. * Force the stencil to the normal expected value for none glowing parts
  83186. */
  83187. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  83188. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  83189. };
  83190. /**
  83191. * Free any resources and references associated to a mesh.
  83192. * Internal use
  83193. * @param mesh The mesh to free.
  83194. */
  83195. HighlightLayer.prototype._disposeMesh = function (mesh) {
  83196. this.removeMesh(mesh);
  83197. this.removeExcludedMesh(mesh);
  83198. };
  83199. /**
  83200. * Dispose the highlight layer and free resources.
  83201. */
  83202. HighlightLayer.prototype.dispose = function () {
  83203. if (this._meshes) {
  83204. // Clean mesh references
  83205. for (var id in this._meshes) {
  83206. var meshHighlight = this._meshes[id];
  83207. if (meshHighlight && meshHighlight.mesh) {
  83208. if (meshHighlight.observerHighlight) {
  83209. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83210. }
  83211. if (meshHighlight.observerDefault) {
  83212. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83213. }
  83214. }
  83215. }
  83216. this._meshes = null;
  83217. }
  83218. if (this._excludedMeshes) {
  83219. for (var id in this._excludedMeshes) {
  83220. var meshHighlight = this._excludedMeshes[id];
  83221. if (meshHighlight) {
  83222. if (meshHighlight.beforeRender) {
  83223. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  83224. }
  83225. if (meshHighlight.afterRender) {
  83226. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  83227. }
  83228. }
  83229. }
  83230. this._excludedMeshes = null;
  83231. }
  83232. _super.prototype.dispose.call(this);
  83233. };
  83234. /**
  83235. * Effect Name of the highlight layer.
  83236. */
  83237. HighlightLayer.EffectName = "HighlightLayer";
  83238. /**
  83239. * The neutral color used during the preparation of the glow effect.
  83240. * This is black by default as the blend operation is a blend operation.
  83241. */
  83242. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  83243. /**
  83244. * Stencil value used for glowing meshes.
  83245. */
  83246. HighlightLayer.GlowingMeshStencilReference = 0x02;
  83247. /**
  83248. * Stencil value used for the other meshes in the scene.
  83249. */
  83250. HighlightLayer.NormalMeshStencilReference = 0x01;
  83251. return HighlightLayer;
  83252. }(BABYLON.EffectLayer));
  83253. BABYLON.HighlightLayer = HighlightLayer;
  83254. })(BABYLON || (BABYLON = {}));
  83255. //# sourceMappingURL=babylon.highlightLayer.js.map
  83256. var __assign = (this && this.__assign) || Object.assign || function(t) {
  83257. for (var s, i = 1, n = arguments.length; i < n; i++) {
  83258. s = arguments[i];
  83259. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  83260. t[p] = s[p];
  83261. }
  83262. return t;
  83263. };
  83264. var BABYLON;
  83265. (function (BABYLON) {
  83266. /**
  83267. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  83268. *
  83269. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  83270. * glowy meshes to your scene.
  83271. *
  83272. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  83273. */
  83274. var GlowLayer = /** @class */ (function (_super) {
  83275. __extends(GlowLayer, _super);
  83276. /**
  83277. * Instantiates a new glow Layer and references it to the scene.
  83278. * @param name The name of the layer
  83279. * @param scene The scene to use the layer in
  83280. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  83281. */
  83282. function GlowLayer(name, scene, options) {
  83283. var _this = _super.call(this, name, scene) || this;
  83284. _this.name = name;
  83285. _this._intensity = 1.0;
  83286. _this._includedOnlyMeshes = [];
  83287. _this._excludedMeshes = [];
  83288. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  83289. // Adapt options
  83290. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  83291. // Initialize the layer
  83292. _this._init({
  83293. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  83294. camera: _this._options.camera,
  83295. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  83296. mainTextureRatio: _this._options.mainTextureRatio
  83297. });
  83298. return _this;
  83299. }
  83300. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  83301. /**
  83302. * Gets the kernel size of the blur.
  83303. */
  83304. get: function () {
  83305. return this._horizontalBlurPostprocess1.kernel;
  83306. },
  83307. /**
  83308. * Sets the kernel size of the blur.
  83309. */
  83310. set: function (value) {
  83311. this._horizontalBlurPostprocess1.kernel = value;
  83312. this._verticalBlurPostprocess1.kernel = value;
  83313. this._horizontalBlurPostprocess2.kernel = value;
  83314. this._verticalBlurPostprocess2.kernel = value;
  83315. },
  83316. enumerable: true,
  83317. configurable: true
  83318. });
  83319. Object.defineProperty(GlowLayer.prototype, "intensity", {
  83320. /**
  83321. * Gets the glow intensity.
  83322. */
  83323. get: function () {
  83324. return this._intensity;
  83325. },
  83326. /**
  83327. * Sets the glow intensity.
  83328. */
  83329. set: function (value) {
  83330. this._intensity = value;
  83331. },
  83332. enumerable: true,
  83333. configurable: true
  83334. });
  83335. /**
  83336. * Get the effect name of the layer.
  83337. * @return The effect name
  83338. */
  83339. GlowLayer.prototype.getEffectName = function () {
  83340. return GlowLayer.EffectName;
  83341. };
  83342. /**
  83343. * Create the merge effect. This is the shader use to blit the information back
  83344. * to the main canvas at the end of the scene rendering.
  83345. */
  83346. GlowLayer.prototype._createMergeEffect = function () {
  83347. // Effect
  83348. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  83349. };
  83350. /**
  83351. * Creates the render target textures and post processes used in the glow layer.
  83352. */
  83353. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  83354. var _this = this;
  83355. var blurTextureWidth = this._mainTextureDesiredSize.width;
  83356. var blurTextureHeight = this._mainTextureDesiredSize.height;
  83357. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83358. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83359. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  83360. width: blurTextureWidth,
  83361. height: blurTextureHeight
  83362. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83363. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83364. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83365. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83366. this._blurTexture1.renderParticles = false;
  83367. this._blurTexture1.ignoreCameraViewport = true;
  83368. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  83369. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  83370. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  83371. width: blurTextureWidth2,
  83372. height: blurTextureHeight2
  83373. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83374. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83375. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83376. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83377. this._blurTexture2.renderParticles = false;
  83378. this._blurTexture2.ignoreCameraViewport = true;
  83379. this._textures = [this._blurTexture1, this._blurTexture2];
  83380. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83381. width: blurTextureWidth,
  83382. height: blurTextureHeight
  83383. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83384. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  83385. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  83386. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  83387. effect.setTexture("textureSampler", _this._mainTexture);
  83388. });
  83389. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83390. width: blurTextureWidth,
  83391. height: blurTextureHeight
  83392. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83393. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83394. width: blurTextureWidth2,
  83395. height: blurTextureHeight2
  83396. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83397. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  83398. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  83399. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  83400. effect.setTexture("textureSampler", _this._blurTexture1);
  83401. });
  83402. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83403. width: blurTextureWidth2,
  83404. height: blurTextureHeight2
  83405. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83406. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83407. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  83408. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83409. this._mainTexture.samples = this._options.mainTextureSamples;
  83410. this._mainTexture.onAfterUnbindObservable.add(function () {
  83411. var internalTexture = _this._blurTexture1.getInternalTexture();
  83412. if (internalTexture) {
  83413. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  83414. internalTexture = _this._blurTexture2.getInternalTexture();
  83415. if (internalTexture) {
  83416. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  83417. }
  83418. }
  83419. });
  83420. // Prevent autoClear.
  83421. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83422. };
  83423. /**
  83424. * Checks for the readiness of the element composing the layer.
  83425. * @param subMesh the mesh to check for
  83426. * @param useInstances specify wether or not to use instances to render the mesh
  83427. * @param emissiveTexture the associated emissive texture used to generate the glow
  83428. * @return true if ready otherwise, false
  83429. */
  83430. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  83431. var material = subMesh.getMaterial();
  83432. var mesh = subMesh.getRenderingMesh();
  83433. if (!material || !mesh) {
  83434. return false;
  83435. }
  83436. var emissiveTexture = material.emissiveTexture;
  83437. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83438. };
  83439. /**
  83440. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83441. */
  83442. GlowLayer.prototype.needStencil = function () {
  83443. return false;
  83444. };
  83445. /**
  83446. * Implementation specific of rendering the generating effect on the main canvas.
  83447. * @param effect The effect used to render through
  83448. */
  83449. GlowLayer.prototype._internalRender = function (effect) {
  83450. // Texture
  83451. effect.setTexture("textureSampler", this._blurTexture1);
  83452. effect.setTexture("textureSampler2", this._blurTexture2);
  83453. effect.setFloat("offset", this._intensity);
  83454. // Cache
  83455. var engine = this._engine;
  83456. var previousStencilBuffer = engine.getStencilBuffer();
  83457. // Draw order
  83458. engine.setStencilBuffer(false);
  83459. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83460. // Draw order
  83461. engine.setStencilBuffer(previousStencilBuffer);
  83462. };
  83463. /**
  83464. * Sets the required values for both the emissive texture and and the main color.
  83465. */
  83466. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83467. var textureLevel = 1.0;
  83468. if (material) {
  83469. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83470. if (this._emissiveTextureAndColor.texture) {
  83471. textureLevel = this._emissiveTextureAndColor.texture.level;
  83472. }
  83473. }
  83474. else {
  83475. this._emissiveTextureAndColor.texture = null;
  83476. }
  83477. if (material.emissiveColor) {
  83478. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  83479. }
  83480. else {
  83481. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83482. }
  83483. };
  83484. /**
  83485. * Returns true if the mesh should render, otherwise false.
  83486. * @param mesh The mesh to render
  83487. * @returns true if it should render otherwise false
  83488. */
  83489. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  83490. return this.hasMesh(mesh);
  83491. };
  83492. /**
  83493. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  83494. * @param mesh The mesh to exclude from the glow layer
  83495. */
  83496. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  83497. if (this._excludedMeshes.indexOf(mesh.uniqueId) !== -1) {
  83498. this._excludedMeshes.push(mesh.uniqueId);
  83499. }
  83500. };
  83501. /**
  83502. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  83503. * @param mesh The mesh to remove
  83504. */
  83505. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  83506. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  83507. if (index !== -1) {
  83508. this._excludedMeshes.splice(index, 1);
  83509. }
  83510. };
  83511. /**
  83512. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  83513. * @param mesh The mesh to include in the glow layer
  83514. */
  83515. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  83516. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1) {
  83517. this._includedOnlyMeshes.push(mesh.uniqueId);
  83518. }
  83519. };
  83520. /**
  83521. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  83522. * @param mesh The mesh to remove
  83523. */
  83524. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  83525. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  83526. if (index !== -1) {
  83527. this._includedOnlyMeshes.splice(index, 1);
  83528. }
  83529. };
  83530. /**
  83531. * Determine if a given mesh will be used in the glow layer
  83532. * @param mesh The mesh to test
  83533. * @returns true if the mesh will be highlighted by the current glow layer
  83534. */
  83535. GlowLayer.prototype.hasMesh = function (mesh) {
  83536. // Included Mesh
  83537. if (this._includedOnlyMeshes.length) {
  83538. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  83539. }
  83540. ;
  83541. // Excluded Mesh
  83542. if (this._excludedMeshes.length) {
  83543. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  83544. }
  83545. ;
  83546. return true;
  83547. };
  83548. /**
  83549. * Free any resources and references associated to a mesh.
  83550. * Internal use
  83551. * @param mesh The mesh to free.
  83552. */
  83553. GlowLayer.prototype._disposeMesh = function (mesh) {
  83554. this.removeIncludedOnlyMesh(mesh);
  83555. this.removeExcludedMesh(mesh);
  83556. };
  83557. /**
  83558. * Effect Name of the layer.
  83559. */
  83560. GlowLayer.EffectName = "GlowLayer";
  83561. /**
  83562. * The default blur kernel size used for the glow.
  83563. */
  83564. GlowLayer.DefaultBlurKernelSize = 32;
  83565. /**
  83566. * The default texture size ratio used for the glow.
  83567. */
  83568. GlowLayer.DefaultTextureRatio = 0.5;
  83569. return GlowLayer;
  83570. }(BABYLON.EffectLayer));
  83571. BABYLON.GlowLayer = GlowLayer;
  83572. })(BABYLON || (BABYLON = {}));
  83573. //# sourceMappingURL=babylon.glowLayer.js.map
  83574. var BABYLON;
  83575. (function (BABYLON) {
  83576. /**
  83577. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  83578. */
  83579. var AssetTaskState;
  83580. (function (AssetTaskState) {
  83581. /**
  83582. * Initialization
  83583. */
  83584. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  83585. /**
  83586. * Running
  83587. */
  83588. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  83589. /**
  83590. * Done
  83591. */
  83592. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  83593. /**
  83594. * Error
  83595. */
  83596. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  83597. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  83598. /**
  83599. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  83600. */
  83601. var AbstractAssetTask = /** @class */ (function () {
  83602. /**
  83603. * Creates a new {BABYLON.AssetsManager}
  83604. * @param name defines the name of the task
  83605. */
  83606. function AbstractAssetTask(
  83607. /**
  83608. * Task name
  83609. */ name) {
  83610. this.name = name;
  83611. this._isCompleted = false;
  83612. this._taskState = AssetTaskState.INIT;
  83613. }
  83614. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  83615. /**
  83616. * Get if the task is completed
  83617. */
  83618. get: function () {
  83619. return this._isCompleted;
  83620. },
  83621. enumerable: true,
  83622. configurable: true
  83623. });
  83624. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  83625. /**
  83626. * Gets the current state of the task
  83627. */
  83628. get: function () {
  83629. return this._taskState;
  83630. },
  83631. enumerable: true,
  83632. configurable: true
  83633. });
  83634. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  83635. /**
  83636. * Gets the current error object (if task is in error)
  83637. */
  83638. get: function () {
  83639. return this._errorObject;
  83640. },
  83641. enumerable: true,
  83642. configurable: true
  83643. });
  83644. /**
  83645. * Internal only
  83646. * @ignore
  83647. */
  83648. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  83649. if (this._errorObject) {
  83650. return;
  83651. }
  83652. this._errorObject = {
  83653. message: message,
  83654. exception: exception
  83655. };
  83656. };
  83657. /**
  83658. * Execute the current task
  83659. * @param scene defines the scene where you want your assets to be loaded
  83660. * @param onSuccess is a callback called when the task is successfully executed
  83661. * @param onError is a callback called if an error occurs
  83662. */
  83663. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  83664. var _this = this;
  83665. this._taskState = AssetTaskState.RUNNING;
  83666. this.runTask(scene, function () {
  83667. _this.onDoneCallback(onSuccess, onError);
  83668. }, function (msg, exception) {
  83669. _this.onErrorCallback(onError, msg, exception);
  83670. });
  83671. };
  83672. /**
  83673. * Execute the current task
  83674. * @param scene defines the scene where you want your assets to be loaded
  83675. * @param onSuccess is a callback called when the task is successfully executed
  83676. * @param onError is a callback called if an error occurs
  83677. */
  83678. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83679. throw new Error("runTask is not implemented");
  83680. };
  83681. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  83682. this._taskState = AssetTaskState.ERROR;
  83683. this._errorObject = {
  83684. message: message,
  83685. exception: exception
  83686. };
  83687. if (this.onError) {
  83688. this.onError(this, message, exception);
  83689. }
  83690. onError();
  83691. };
  83692. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  83693. try {
  83694. this._taskState = AssetTaskState.DONE;
  83695. this._isCompleted = true;
  83696. if (this.onSuccess) {
  83697. this.onSuccess(this);
  83698. }
  83699. onSuccess();
  83700. }
  83701. catch (e) {
  83702. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  83703. }
  83704. };
  83705. return AbstractAssetTask;
  83706. }());
  83707. BABYLON.AbstractAssetTask = AbstractAssetTask;
  83708. /**
  83709. * Class used to share progress information about assets loading
  83710. */
  83711. var AssetsProgressEvent = /** @class */ (function () {
  83712. /**
  83713. * Creates a {BABYLON.AssetsProgressEvent}
  83714. * @param remainingCount defines the number of remaining tasks to process
  83715. * @param totalCount defines the total number of tasks
  83716. * @param task defines the task that was just processed
  83717. */
  83718. function AssetsProgressEvent(remainingCount, totalCount, task) {
  83719. this.remainingCount = remainingCount;
  83720. this.totalCount = totalCount;
  83721. this.task = task;
  83722. }
  83723. return AssetsProgressEvent;
  83724. }());
  83725. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  83726. /**
  83727. * Define a task used by {BABYLON.AssetsManager} to load meshes
  83728. */
  83729. var MeshAssetTask = /** @class */ (function (_super) {
  83730. __extends(MeshAssetTask, _super);
  83731. /**
  83732. * Creates a new {BABYLON.MeshAssetTask}
  83733. * @param name defines the name of the task
  83734. * @param meshesNames defines the list of mesh's names you want to load
  83735. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  83736. * @param sceneFilename defines the filename of the scene to load from
  83737. */
  83738. function MeshAssetTask(
  83739. /**
  83740. * Defines the name of the task
  83741. */
  83742. name,
  83743. /**
  83744. * Defines the list of mesh's names you want to load
  83745. */
  83746. meshesNames,
  83747. /**
  83748. * Defines the root url to use as a base to load your meshes and associated resources
  83749. */
  83750. rootUrl,
  83751. /**
  83752. * Defines the filename of the scene to load from
  83753. */
  83754. sceneFilename) {
  83755. var _this = _super.call(this, name) || this;
  83756. _this.name = name;
  83757. _this.meshesNames = meshesNames;
  83758. _this.rootUrl = rootUrl;
  83759. _this.sceneFilename = sceneFilename;
  83760. return _this;
  83761. }
  83762. /**
  83763. * Execute the current task
  83764. * @param scene defines the scene where you want your assets to be loaded
  83765. * @param onSuccess is a callback called when the task is successfully executed
  83766. * @param onError is a callback called if an error occurs
  83767. */
  83768. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83769. var _this = this;
  83770. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  83771. _this.loadedMeshes = meshes;
  83772. _this.loadedParticleSystems = particleSystems;
  83773. _this.loadedSkeletons = skeletons;
  83774. onSuccess();
  83775. }, null, function (scene, message, exception) {
  83776. onError(message, exception);
  83777. });
  83778. };
  83779. return MeshAssetTask;
  83780. }(AbstractAssetTask));
  83781. BABYLON.MeshAssetTask = MeshAssetTask;
  83782. /**
  83783. * Define a task used by {BABYLON.AssetsManager} to load text content
  83784. */
  83785. var TextFileAssetTask = /** @class */ (function (_super) {
  83786. __extends(TextFileAssetTask, _super);
  83787. /**
  83788. * Creates a new TextFileAssetTask object
  83789. * @param name defines the name of the task
  83790. * @param url defines the location of the file to load
  83791. */
  83792. function TextFileAssetTask(
  83793. /**
  83794. * Defines the name of the task
  83795. */
  83796. name,
  83797. /**
  83798. * Defines the location of the file to load
  83799. */
  83800. url) {
  83801. var _this = _super.call(this, name) || this;
  83802. _this.name = name;
  83803. _this.url = url;
  83804. return _this;
  83805. }
  83806. /**
  83807. * Execute the current task
  83808. * @param scene defines the scene where you want your assets to be loaded
  83809. * @param onSuccess is a callback called when the task is successfully executed
  83810. * @param onError is a callback called if an error occurs
  83811. */
  83812. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83813. var _this = this;
  83814. scene._loadFile(this.url, function (data) {
  83815. _this.text = data;
  83816. onSuccess();
  83817. }, undefined, false, true, function (request, exception) {
  83818. if (request) {
  83819. onError(request.status + " " + request.statusText, exception);
  83820. }
  83821. });
  83822. };
  83823. return TextFileAssetTask;
  83824. }(AbstractAssetTask));
  83825. BABYLON.TextFileAssetTask = TextFileAssetTask;
  83826. /**
  83827. * Define a task used by {BABYLON.AssetsManager} to load binary data
  83828. */
  83829. var BinaryFileAssetTask = /** @class */ (function (_super) {
  83830. __extends(BinaryFileAssetTask, _super);
  83831. /**
  83832. * Creates a new BinaryFileAssetTask object
  83833. * @param name defines the name of the new task
  83834. * @param url defines the location of the file to load
  83835. */
  83836. function BinaryFileAssetTask(
  83837. /**
  83838. * Defines the name of the task
  83839. */
  83840. name,
  83841. /**
  83842. * Defines the location of the file to load
  83843. */
  83844. url) {
  83845. var _this = _super.call(this, name) || this;
  83846. _this.name = name;
  83847. _this.url = url;
  83848. return _this;
  83849. }
  83850. /**
  83851. * Execute the current task
  83852. * @param scene defines the scene where you want your assets to be loaded
  83853. * @param onSuccess is a callback called when the task is successfully executed
  83854. * @param onError is a callback called if an error occurs
  83855. */
  83856. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83857. var _this = this;
  83858. scene._loadFile(this.url, function (data) {
  83859. _this.data = data;
  83860. onSuccess();
  83861. }, undefined, true, true, function (request, exception) {
  83862. if (request) {
  83863. onError(request.status + " " + request.statusText, exception);
  83864. }
  83865. });
  83866. };
  83867. return BinaryFileAssetTask;
  83868. }(AbstractAssetTask));
  83869. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  83870. /**
  83871. * Define a task used by {BABYLON.AssetsManager} to load images
  83872. */
  83873. var ImageAssetTask = /** @class */ (function (_super) {
  83874. __extends(ImageAssetTask, _super);
  83875. /**
  83876. * Creates a new ImageAssetTask
  83877. * @param name defines the name of the task
  83878. * @param url defines the location of the image to load
  83879. */
  83880. function ImageAssetTask(
  83881. /**
  83882. * Defines the name of the task
  83883. */
  83884. name,
  83885. /**
  83886. * Defines the location of the image to load
  83887. */
  83888. url) {
  83889. var _this = _super.call(this, name) || this;
  83890. _this.name = name;
  83891. _this.url = url;
  83892. return _this;
  83893. }
  83894. /**
  83895. * Execute the current task
  83896. * @param scene defines the scene where you want your assets to be loaded
  83897. * @param onSuccess is a callback called when the task is successfully executed
  83898. * @param onError is a callback called if an error occurs
  83899. */
  83900. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83901. var _this = this;
  83902. var img = new Image();
  83903. BABYLON.Tools.SetCorsBehavior(this.url, img);
  83904. img.onload = function () {
  83905. _this.image = img;
  83906. onSuccess();
  83907. };
  83908. img.onerror = function (err) {
  83909. onError("Error loading image", err);
  83910. };
  83911. img.src = this.url;
  83912. };
  83913. return ImageAssetTask;
  83914. }(AbstractAssetTask));
  83915. BABYLON.ImageAssetTask = ImageAssetTask;
  83916. /**
  83917. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  83918. */
  83919. var TextureAssetTask = /** @class */ (function (_super) {
  83920. __extends(TextureAssetTask, _super);
  83921. /**
  83922. * Creates a new TextureAssetTask object
  83923. * @param name defines the name of the task
  83924. * @param url defines the location of the file to load
  83925. * @param noMipmap defines if mipmap should not be generated (default is false)
  83926. * @param invertY defines if texture must be inverted on Y axis (default is false)
  83927. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  83928. */
  83929. function TextureAssetTask(
  83930. /**
  83931. * Defines the name of the task
  83932. */
  83933. name,
  83934. /**
  83935. * Defines the location of the file to load
  83936. */
  83937. url,
  83938. /**
  83939. * Defines if mipmap should not be generated (default is false)
  83940. */
  83941. noMipmap,
  83942. /**
  83943. * Defines if texture must be inverted on Y axis (default is false)
  83944. */
  83945. invertY,
  83946. /**
  83947. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  83948. */
  83949. samplingMode) {
  83950. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  83951. var _this = _super.call(this, name) || this;
  83952. _this.name = name;
  83953. _this.url = url;
  83954. _this.noMipmap = noMipmap;
  83955. _this.invertY = invertY;
  83956. _this.samplingMode = samplingMode;
  83957. return _this;
  83958. }
  83959. /**
  83960. * Execute the current task
  83961. * @param scene defines the scene where you want your assets to be loaded
  83962. * @param onSuccess is a callback called when the task is successfully executed
  83963. * @param onError is a callback called if an error occurs
  83964. */
  83965. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83966. var onload = function () {
  83967. onSuccess();
  83968. };
  83969. var onerror = function (message, exception) {
  83970. onError(message, exception);
  83971. };
  83972. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  83973. };
  83974. return TextureAssetTask;
  83975. }(AbstractAssetTask));
  83976. BABYLON.TextureAssetTask = TextureAssetTask;
  83977. /**
  83978. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  83979. */
  83980. var CubeTextureAssetTask = /** @class */ (function (_super) {
  83981. __extends(CubeTextureAssetTask, _super);
  83982. /**
  83983. * Creates a new CubeTextureAssetTask
  83984. * @param name defines the name of the task
  83985. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  83986. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  83987. * @param noMipmap defines if mipmaps should not be generated (default is false)
  83988. * @param files defines the explicit list of files (undefined by default)
  83989. */
  83990. function CubeTextureAssetTask(
  83991. /**
  83992. * Defines the name of the task
  83993. */
  83994. name,
  83995. /**
  83996. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  83997. */
  83998. url,
  83999. /**
  84000. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  84001. */
  84002. extensions,
  84003. /**
  84004. * Defines if mipmaps should not be generated (default is false)
  84005. */
  84006. noMipmap,
  84007. /**
  84008. * Defines the explicit list of files (undefined by default)
  84009. */
  84010. files) {
  84011. var _this = _super.call(this, name) || this;
  84012. _this.name = name;
  84013. _this.url = url;
  84014. _this.extensions = extensions;
  84015. _this.noMipmap = noMipmap;
  84016. _this.files = files;
  84017. return _this;
  84018. }
  84019. /**
  84020. * Execute the current task
  84021. * @param scene defines the scene where you want your assets to be loaded
  84022. * @param onSuccess is a callback called when the task is successfully executed
  84023. * @param onError is a callback called if an error occurs
  84024. */
  84025. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84026. var onload = function () {
  84027. onSuccess();
  84028. };
  84029. var onerror = function (message, exception) {
  84030. onError(message, exception);
  84031. };
  84032. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  84033. };
  84034. return CubeTextureAssetTask;
  84035. }(AbstractAssetTask));
  84036. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  84037. /**
  84038. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  84039. */
  84040. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  84041. __extends(HDRCubeTextureAssetTask, _super);
  84042. /**
  84043. * Creates a new HDRCubeTextureAssetTask object
  84044. * @param name defines the name of the task
  84045. * @param url defines the location of the file to load
  84046. * @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.
  84047. * @param noMipmap defines if mipmaps should not be generated (default is false)
  84048. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  84049. * @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)
  84050. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  84051. */
  84052. function HDRCubeTextureAssetTask(
  84053. /**
  84054. * Defines the name of the task
  84055. */
  84056. name,
  84057. /**
  84058. * Defines the location of the file to load
  84059. */
  84060. url,
  84061. /**
  84062. * 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.
  84063. */
  84064. size,
  84065. /**
  84066. * Defines if mipmaps should not be generated (default is false)
  84067. */
  84068. noMipmap,
  84069. /**
  84070. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  84071. */
  84072. generateHarmonics,
  84073. /**
  84074. * 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)
  84075. */
  84076. useInGammaSpace,
  84077. /**
  84078. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  84079. */
  84080. usePMREMGenerator) {
  84081. if (noMipmap === void 0) { noMipmap = false; }
  84082. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84083. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84084. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84085. var _this = _super.call(this, name) || this;
  84086. _this.name = name;
  84087. _this.url = url;
  84088. _this.size = size;
  84089. _this.noMipmap = noMipmap;
  84090. _this.generateHarmonics = generateHarmonics;
  84091. _this.useInGammaSpace = useInGammaSpace;
  84092. _this.usePMREMGenerator = usePMREMGenerator;
  84093. return _this;
  84094. }
  84095. /**
  84096. * Execute the current task
  84097. * @param scene defines the scene where you want your assets to be loaded
  84098. * @param onSuccess is a callback called when the task is successfully executed
  84099. * @param onError is a callback called if an error occurs
  84100. */
  84101. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  84102. var onload = function () {
  84103. onSuccess();
  84104. };
  84105. var onerror = function (message, exception) {
  84106. onError(message, exception);
  84107. };
  84108. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  84109. };
  84110. return HDRCubeTextureAssetTask;
  84111. }(AbstractAssetTask));
  84112. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  84113. /**
  84114. * This class can be used to easily import assets into a scene
  84115. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  84116. */
  84117. var AssetsManager = /** @class */ (function () {
  84118. /**
  84119. * Creates a new AssetsManager
  84120. * @param scene defines the scene to work on
  84121. */
  84122. function AssetsManager(scene) {
  84123. this._isLoading = false;
  84124. this._tasks = new Array();
  84125. this._waitingTasksCount = 0;
  84126. this._totalTasksCount = 0;
  84127. /**
  84128. * Observable called when all tasks are processed
  84129. */
  84130. this.onTaskSuccessObservable = new BABYLON.Observable();
  84131. /**
  84132. * Observable called when a task had an error
  84133. */
  84134. this.onTaskErrorObservable = new BABYLON.Observable();
  84135. /**
  84136. * Observable called when a task is successful
  84137. */
  84138. this.onTasksDoneObservable = new BABYLON.Observable();
  84139. /**
  84140. * Observable called when a task is done (whatever the result is)
  84141. */
  84142. this.onProgressObservable = new BABYLON.Observable();
  84143. /**
  84144. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  84145. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  84146. */
  84147. this.useDefaultLoadingScreen = true;
  84148. this._scene = scene;
  84149. }
  84150. /**
  84151. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  84152. * @param taskName defines the name of the new task
  84153. * @param meshesNames defines the name of meshes to load
  84154. * @param rootUrl defines the root url to use to locate files
  84155. * @param sceneFilename defines the filename of the scene file
  84156. * @returns a new {BABYLON.MeshAssetTask} object
  84157. */
  84158. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  84159. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  84160. this._tasks.push(task);
  84161. return task;
  84162. };
  84163. /**
  84164. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  84165. * @param taskName defines the name of the new task
  84166. * @param url defines the url of the file to load
  84167. * @returns a new {BABYLON.TextFileAssetTask} object
  84168. */
  84169. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  84170. var task = new TextFileAssetTask(taskName, url);
  84171. this._tasks.push(task);
  84172. return task;
  84173. };
  84174. /**
  84175. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  84176. * @param taskName defines the name of the new task
  84177. * @param url defines the url of the file to load
  84178. * @returns a new {BABYLON.BinaryFileAssetTask} object
  84179. */
  84180. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  84181. var task = new BinaryFileAssetTask(taskName, url);
  84182. this._tasks.push(task);
  84183. return task;
  84184. };
  84185. /**
  84186. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  84187. * @param taskName defines the name of the new task
  84188. * @param url defines the url of the file to load
  84189. * @returns a new {BABYLON.ImageAssetTask} object
  84190. */
  84191. AssetsManager.prototype.addImageTask = function (taskName, url) {
  84192. var task = new ImageAssetTask(taskName, url);
  84193. this._tasks.push(task);
  84194. return task;
  84195. };
  84196. /**
  84197. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  84198. * @param taskName defines the name of the new task
  84199. * @param url defines the url of the file to load
  84200. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84201. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  84202. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  84203. * @returns a new {BABYLON.TextureAssetTask} object
  84204. */
  84205. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  84206. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84207. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  84208. this._tasks.push(task);
  84209. return task;
  84210. };
  84211. /**
  84212. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  84213. * @param taskName defines the name of the new task
  84214. * @param url defines the url of the file to load
  84215. * @param extensions defines the extension to use to load the cube map (can be null)
  84216. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84217. * @param files defines the list of files to load (can be null)
  84218. * @returns a new {BABYLON.CubeTextureAssetTask} object
  84219. */
  84220. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  84221. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  84222. this._tasks.push(task);
  84223. return task;
  84224. };
  84225. /**
  84226. *
  84227. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  84228. * @param taskName defines the name of the new task
  84229. * @param url defines the url of the file to load
  84230. * @param size defines the size you want for the cubemap (can be null)
  84231. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84232. * @param generateHarmonics defines if you want to automatically generate (true by default)
  84233. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  84234. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  84235. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  84236. */
  84237. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  84238. if (noMipmap === void 0) { noMipmap = false; }
  84239. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84240. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84241. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84242. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  84243. this._tasks.push(task);
  84244. return task;
  84245. };
  84246. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  84247. var _this = this;
  84248. this._waitingTasksCount--;
  84249. try {
  84250. if (task.taskState === AssetTaskState.DONE) {
  84251. // Let's remove successfull tasks
  84252. BABYLON.Tools.SetImmediate(function () {
  84253. var index = _this._tasks.indexOf(task);
  84254. if (index > -1) {
  84255. _this._tasks.splice(index, 1);
  84256. }
  84257. });
  84258. }
  84259. if (this.onProgress) {
  84260. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  84261. }
  84262. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  84263. }
  84264. catch (e) {
  84265. BABYLON.Tools.Error("Error running progress callbacks.");
  84266. console.log(e);
  84267. }
  84268. if (this._waitingTasksCount === 0) {
  84269. try {
  84270. if (this.onFinish) {
  84271. this.onFinish(this._tasks);
  84272. }
  84273. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84274. }
  84275. catch (e) {
  84276. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  84277. console.log(e);
  84278. }
  84279. this._isLoading = false;
  84280. this._scene.getEngine().hideLoadingUI();
  84281. }
  84282. };
  84283. AssetsManager.prototype._runTask = function (task) {
  84284. var _this = this;
  84285. var done = function () {
  84286. try {
  84287. if (_this.onTaskSuccess) {
  84288. _this.onTaskSuccess(task);
  84289. }
  84290. _this.onTaskSuccessObservable.notifyObservers(task);
  84291. _this._decreaseWaitingTasksCount(task);
  84292. }
  84293. catch (e) {
  84294. error("Error executing task success callbacks", e);
  84295. }
  84296. };
  84297. var error = function (message, exception) {
  84298. task._setErrorObject(message, exception);
  84299. if (_this.onTaskError) {
  84300. _this.onTaskError(task);
  84301. }
  84302. _this.onTaskErrorObservable.notifyObservers(task);
  84303. _this._decreaseWaitingTasksCount(task);
  84304. };
  84305. task.run(this._scene, done, error);
  84306. };
  84307. /**
  84308. * Reset the {BABYLON.AssetsManager} and remove all tasks
  84309. * @return the current instance of the {BABYLON.AssetsManager}
  84310. */
  84311. AssetsManager.prototype.reset = function () {
  84312. this._isLoading = false;
  84313. this._tasks = new Array();
  84314. return this;
  84315. };
  84316. /**
  84317. * Start the loading process
  84318. * @return the current instance of the {BABYLON.AssetsManager}
  84319. */
  84320. AssetsManager.prototype.load = function () {
  84321. if (this._isLoading) {
  84322. return this;
  84323. }
  84324. this._isLoading = true;
  84325. this._waitingTasksCount = this._tasks.length;
  84326. this._totalTasksCount = this._tasks.length;
  84327. if (this._waitingTasksCount === 0) {
  84328. if (this.onFinish) {
  84329. this.onFinish(this._tasks);
  84330. }
  84331. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84332. return this;
  84333. }
  84334. if (this.useDefaultLoadingScreen) {
  84335. this._scene.getEngine().displayLoadingUI();
  84336. }
  84337. for (var index = 0; index < this._tasks.length; index++) {
  84338. var task = this._tasks[index];
  84339. this._runTask(task);
  84340. }
  84341. return this;
  84342. };
  84343. return AssetsManager;
  84344. }());
  84345. BABYLON.AssetsManager = AssetsManager;
  84346. })(BABYLON || (BABYLON = {}));
  84347. //# sourceMappingURL=babylon.assetsManager.js.map
  84348. var BABYLON;
  84349. (function (BABYLON) {
  84350. var serializedGeometries = [];
  84351. var serializeGeometry = function (geometry, serializationGeometries) {
  84352. if (serializedGeometries[geometry.id]) {
  84353. return;
  84354. }
  84355. if (geometry.doNotSerialize) {
  84356. return;
  84357. }
  84358. if (geometry instanceof BABYLON.BoxGeometry) {
  84359. serializationGeometries.boxes.push(geometry.serialize());
  84360. }
  84361. else if (geometry instanceof BABYLON.SphereGeometry) {
  84362. serializationGeometries.spheres.push(geometry.serialize());
  84363. }
  84364. else if (geometry instanceof BABYLON.CylinderGeometry) {
  84365. serializationGeometries.cylinders.push(geometry.serialize());
  84366. }
  84367. else if (geometry instanceof BABYLON.TorusGeometry) {
  84368. serializationGeometries.toruses.push(geometry.serialize());
  84369. }
  84370. else if (geometry instanceof BABYLON.GroundGeometry) {
  84371. serializationGeometries.grounds.push(geometry.serialize());
  84372. }
  84373. else if (geometry instanceof BABYLON.Plane) {
  84374. serializationGeometries.planes.push(geometry.serialize());
  84375. }
  84376. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  84377. serializationGeometries.torusKnots.push(geometry.serialize());
  84378. }
  84379. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  84380. throw new Error("Unknown primitive type");
  84381. }
  84382. else {
  84383. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  84384. }
  84385. serializedGeometries[geometry.id] = true;
  84386. };
  84387. var serializeMesh = function (mesh, serializationScene) {
  84388. var serializationObject = {};
  84389. // Geometry
  84390. var geometry = mesh._geometry;
  84391. if (geometry) {
  84392. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  84393. // 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
  84394. serializeGeometry(geometry, serializationScene.geometries);
  84395. }
  84396. }
  84397. // Custom
  84398. if (mesh.serialize) {
  84399. mesh.serialize(serializationObject);
  84400. }
  84401. return serializationObject;
  84402. };
  84403. var finalizeSingleMesh = function (mesh, serializationObject) {
  84404. //only works if the mesh is already loaded
  84405. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84406. //serialize material
  84407. if (mesh.material) {
  84408. if (mesh.material instanceof BABYLON.StandardMaterial) {
  84409. serializationObject.materials = serializationObject.materials || [];
  84410. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84411. serializationObject.materials.push(mesh.material.serialize());
  84412. }
  84413. }
  84414. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  84415. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  84416. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84417. serializationObject.multiMaterials.push(mesh.material.serialize());
  84418. }
  84419. }
  84420. }
  84421. //serialize geometry
  84422. var geometry = mesh._geometry;
  84423. if (geometry) {
  84424. if (!serializationObject.geometries) {
  84425. serializationObject.geometries = {};
  84426. serializationObject.geometries.boxes = [];
  84427. serializationObject.geometries.spheres = [];
  84428. serializationObject.geometries.cylinders = [];
  84429. serializationObject.geometries.toruses = [];
  84430. serializationObject.geometries.grounds = [];
  84431. serializationObject.geometries.planes = [];
  84432. serializationObject.geometries.torusKnots = [];
  84433. serializationObject.geometries.vertexData = [];
  84434. }
  84435. serializeGeometry(geometry, serializationObject.geometries);
  84436. }
  84437. // Skeletons
  84438. if (mesh.skeleton) {
  84439. serializationObject.skeletons = serializationObject.skeletons || [];
  84440. serializationObject.skeletons.push(mesh.skeleton.serialize());
  84441. }
  84442. //serialize the actual mesh
  84443. serializationObject.meshes = serializationObject.meshes || [];
  84444. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84445. }
  84446. };
  84447. var SceneSerializer = /** @class */ (function () {
  84448. function SceneSerializer() {
  84449. }
  84450. SceneSerializer.ClearCache = function () {
  84451. serializedGeometries = [];
  84452. };
  84453. SceneSerializer.Serialize = function (scene) {
  84454. var serializationObject = {};
  84455. SceneSerializer.ClearCache();
  84456. // Scene
  84457. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  84458. serializationObject.autoClear = scene.autoClear;
  84459. serializationObject.clearColor = scene.clearColor.asArray();
  84460. serializationObject.ambientColor = scene.ambientColor.asArray();
  84461. serializationObject.gravity = scene.gravity.asArray();
  84462. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  84463. serializationObject.workerCollisions = scene.workerCollisions;
  84464. // Fog
  84465. if (scene.fogMode && scene.fogMode !== 0) {
  84466. serializationObject.fogMode = scene.fogMode;
  84467. serializationObject.fogColor = scene.fogColor.asArray();
  84468. serializationObject.fogStart = scene.fogStart;
  84469. serializationObject.fogEnd = scene.fogEnd;
  84470. serializationObject.fogDensity = scene.fogDensity;
  84471. }
  84472. //Physics
  84473. if (scene.isPhysicsEnabled()) {
  84474. var physicEngine = scene.getPhysicsEngine();
  84475. if (physicEngine) {
  84476. serializationObject.physicsEnabled = true;
  84477. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  84478. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  84479. }
  84480. }
  84481. // Metadata
  84482. if (scene.metadata) {
  84483. serializationObject.metadata = scene.metadata;
  84484. }
  84485. // Morph targets
  84486. serializationObject.morphTargetManagers = [];
  84487. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  84488. var abstractMesh = _a[_i];
  84489. var manager = abstractMesh.morphTargetManager;
  84490. if (manager) {
  84491. serializationObject.morphTargetManagers.push(manager.serialize());
  84492. }
  84493. }
  84494. // Lights
  84495. serializationObject.lights = [];
  84496. var index;
  84497. var light;
  84498. for (index = 0; index < scene.lights.length; index++) {
  84499. light = scene.lights[index];
  84500. if (!light.doNotSerialize) {
  84501. serializationObject.lights.push(light.serialize());
  84502. }
  84503. }
  84504. // Cameras
  84505. serializationObject.cameras = [];
  84506. for (index = 0; index < scene.cameras.length; index++) {
  84507. var camera = scene.cameras[index];
  84508. if (!camera.doNotSerialize) {
  84509. serializationObject.cameras.push(camera.serialize());
  84510. }
  84511. }
  84512. if (scene.activeCamera) {
  84513. serializationObject.activeCameraID = scene.activeCamera.id;
  84514. }
  84515. // Animations
  84516. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  84517. // Materials
  84518. serializationObject.materials = [];
  84519. serializationObject.multiMaterials = [];
  84520. var material;
  84521. for (index = 0; index < scene.materials.length; index++) {
  84522. material = scene.materials[index];
  84523. if (!material.doNotSerialize) {
  84524. serializationObject.materials.push(material.serialize());
  84525. }
  84526. }
  84527. // MultiMaterials
  84528. serializationObject.multiMaterials = [];
  84529. for (index = 0; index < scene.multiMaterials.length; index++) {
  84530. var multiMaterial = scene.multiMaterials[index];
  84531. serializationObject.multiMaterials.push(multiMaterial.serialize());
  84532. }
  84533. // Environment texture
  84534. if (scene.environmentTexture) {
  84535. serializationObject.environmentTexture = scene.environmentTexture.name;
  84536. }
  84537. // Skeletons
  84538. serializationObject.skeletons = [];
  84539. for (index = 0; index < scene.skeletons.length; index++) {
  84540. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  84541. }
  84542. // Transform nodes
  84543. serializationObject.transformNodes = [];
  84544. for (index = 0; index < scene.transformNodes.length; index++) {
  84545. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  84546. }
  84547. // Geometries
  84548. serializationObject.geometries = {};
  84549. serializationObject.geometries.boxes = [];
  84550. serializationObject.geometries.spheres = [];
  84551. serializationObject.geometries.cylinders = [];
  84552. serializationObject.geometries.toruses = [];
  84553. serializationObject.geometries.grounds = [];
  84554. serializationObject.geometries.planes = [];
  84555. serializationObject.geometries.torusKnots = [];
  84556. serializationObject.geometries.vertexData = [];
  84557. serializedGeometries = [];
  84558. var geometries = scene.getGeometries();
  84559. for (index = 0; index < geometries.length; index++) {
  84560. var geometry = geometries[index];
  84561. if (geometry.isReady()) {
  84562. serializeGeometry(geometry, serializationObject.geometries);
  84563. }
  84564. }
  84565. // Meshes
  84566. serializationObject.meshes = [];
  84567. for (index = 0; index < scene.meshes.length; index++) {
  84568. var abstractMesh = scene.meshes[index];
  84569. if (abstractMesh instanceof BABYLON.Mesh) {
  84570. var mesh = abstractMesh;
  84571. if (!mesh.doNotSerialize) {
  84572. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84573. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84574. }
  84575. }
  84576. }
  84577. }
  84578. // Particles Systems
  84579. serializationObject.particleSystems = [];
  84580. for (index = 0; index < scene.particleSystems.length; index++) {
  84581. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  84582. }
  84583. // Lens flares
  84584. serializationObject.lensFlareSystems = [];
  84585. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  84586. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  84587. }
  84588. // Shadows
  84589. serializationObject.shadowGenerators = [];
  84590. for (index = 0; index < scene.lights.length; index++) {
  84591. light = scene.lights[index];
  84592. var shadowGenerator = light.getShadowGenerator();
  84593. if (shadowGenerator) {
  84594. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  84595. }
  84596. }
  84597. // Action Manager
  84598. if (scene.actionManager) {
  84599. serializationObject.actions = scene.actionManager.serialize("scene");
  84600. }
  84601. // Audio
  84602. serializationObject.sounds = [];
  84603. for (index = 0; index < scene.soundTracks.length; index++) {
  84604. var soundtrack = scene.soundTracks[index];
  84605. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  84606. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  84607. }
  84608. }
  84609. return serializationObject;
  84610. };
  84611. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  84612. if (withParents === void 0) { withParents = false; }
  84613. if (withChildren === void 0) { withChildren = false; }
  84614. var serializationObject = {};
  84615. SceneSerializer.ClearCache();
  84616. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  84617. if (withParents || withChildren) {
  84618. //deliberate for loop! not for each, appended should be processed as well.
  84619. for (var i = 0; i < toSerialize.length; ++i) {
  84620. if (withChildren) {
  84621. toSerialize[i].getDescendants().forEach(function (node) {
  84622. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  84623. toSerialize.push(node);
  84624. }
  84625. });
  84626. }
  84627. //make sure the array doesn't contain the object already
  84628. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  84629. toSerialize.push(toSerialize[i].parent);
  84630. }
  84631. }
  84632. }
  84633. toSerialize.forEach(function (mesh) {
  84634. finalizeSingleMesh(mesh, serializationObject);
  84635. });
  84636. return serializationObject;
  84637. };
  84638. return SceneSerializer;
  84639. }());
  84640. BABYLON.SceneSerializer = SceneSerializer;
  84641. })(BABYLON || (BABYLON = {}));
  84642. //# sourceMappingURL=babylon.sceneSerializer.js.map
  84643. var BABYLON;
  84644. (function (BABYLON) {
  84645. var ReflectionProbe = /** @class */ (function () {
  84646. function ReflectionProbe(name, size, scene, generateMipMaps) {
  84647. if (generateMipMaps === void 0) { generateMipMaps = true; }
  84648. var _this = this;
  84649. this.name = name;
  84650. this._viewMatrix = BABYLON.Matrix.Identity();
  84651. this._target = BABYLON.Vector3.Zero();
  84652. this._add = BABYLON.Vector3.Zero();
  84653. this.invertYAxis = false;
  84654. this.position = BABYLON.Vector3.Zero();
  84655. this._scene = scene;
  84656. this._scene.reflectionProbes.push(this);
  84657. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  84658. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  84659. switch (faceIndex) {
  84660. case 0:
  84661. _this._add.copyFromFloats(1, 0, 0);
  84662. break;
  84663. case 1:
  84664. _this._add.copyFromFloats(-1, 0, 0);
  84665. break;
  84666. case 2:
  84667. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  84668. break;
  84669. case 3:
  84670. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  84671. break;
  84672. case 4:
  84673. _this._add.copyFromFloats(0, 0, 1);
  84674. break;
  84675. case 5:
  84676. _this._add.copyFromFloats(0, 0, -1);
  84677. break;
  84678. }
  84679. if (_this._attachedMesh) {
  84680. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  84681. }
  84682. _this.position.addToRef(_this._add, _this._target);
  84683. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  84684. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  84685. scene._forcedViewPosition = _this.position;
  84686. });
  84687. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  84688. scene._forcedViewPosition = null;
  84689. scene.updateTransformMatrix(true);
  84690. });
  84691. if (scene.activeCamera) {
  84692. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  84693. }
  84694. }
  84695. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  84696. get: function () {
  84697. return this._renderTargetTexture.samples;
  84698. },
  84699. set: function (value) {
  84700. this._renderTargetTexture.samples = value;
  84701. },
  84702. enumerable: true,
  84703. configurable: true
  84704. });
  84705. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  84706. get: function () {
  84707. return this._renderTargetTexture.refreshRate;
  84708. },
  84709. set: function (value) {
  84710. this._renderTargetTexture.refreshRate = value;
  84711. },
  84712. enumerable: true,
  84713. configurable: true
  84714. });
  84715. ReflectionProbe.prototype.getScene = function () {
  84716. return this._scene;
  84717. };
  84718. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  84719. get: function () {
  84720. return this._renderTargetTexture;
  84721. },
  84722. enumerable: true,
  84723. configurable: true
  84724. });
  84725. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  84726. get: function () {
  84727. return this._renderTargetTexture.renderList;
  84728. },
  84729. enumerable: true,
  84730. configurable: true
  84731. });
  84732. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  84733. this._attachedMesh = mesh;
  84734. };
  84735. /**
  84736. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  84737. *
  84738. * @param renderingGroupId The rendering group id corresponding to its index
  84739. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  84740. */
  84741. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  84742. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  84743. };
  84744. ReflectionProbe.prototype.dispose = function () {
  84745. var index = this._scene.reflectionProbes.indexOf(this);
  84746. if (index !== -1) {
  84747. // Remove from the scene if found
  84748. this._scene.reflectionProbes.splice(index, 1);
  84749. }
  84750. if (this._renderTargetTexture) {
  84751. this._renderTargetTexture.dispose();
  84752. this._renderTargetTexture = null;
  84753. }
  84754. };
  84755. return ReflectionProbe;
  84756. }());
  84757. BABYLON.ReflectionProbe = ReflectionProbe;
  84758. })(BABYLON || (BABYLON = {}));
  84759. //# sourceMappingURL=babylon.reflectionProbe.js.map
  84760. var BABYLON;
  84761. (function (BABYLON) {
  84762. var Layer = /** @class */ (function () {
  84763. function Layer(name, imgUrl, scene, isBackground, color) {
  84764. this.name = name;
  84765. this.scale = new BABYLON.Vector2(1, 1);
  84766. this.offset = new BABYLON.Vector2(0, 0);
  84767. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  84768. this.layerMask = 0x0FFFFFFF;
  84769. this._vertexBuffers = {};
  84770. // Events
  84771. /**
  84772. * An event triggered when the layer is disposed.
  84773. * @type {BABYLON.Observable}
  84774. */
  84775. this.onDisposeObservable = new BABYLON.Observable();
  84776. /**
  84777. * An event triggered before rendering the scene
  84778. * @type {BABYLON.Observable}
  84779. */
  84780. this.onBeforeRenderObservable = new BABYLON.Observable();
  84781. /**
  84782. * An event triggered after rendering the scene
  84783. * @type {BABYLON.Observable}
  84784. */
  84785. this.onAfterRenderObservable = new BABYLON.Observable();
  84786. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  84787. this.isBackground = isBackground === undefined ? true : isBackground;
  84788. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  84789. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  84790. this._scene.layers.push(this);
  84791. var engine = this._scene.getEngine();
  84792. // VBO
  84793. var vertices = [];
  84794. vertices.push(1, 1);
  84795. vertices.push(-1, 1);
  84796. vertices.push(-1, -1);
  84797. vertices.push(1, -1);
  84798. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84799. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84800. this._createIndexBuffer();
  84801. // Effects
  84802. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  84803. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  84804. }
  84805. Object.defineProperty(Layer.prototype, "onDispose", {
  84806. set: function (callback) {
  84807. if (this._onDisposeObserver) {
  84808. this.onDisposeObservable.remove(this._onDisposeObserver);
  84809. }
  84810. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  84811. },
  84812. enumerable: true,
  84813. configurable: true
  84814. });
  84815. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  84816. set: function (callback) {
  84817. if (this._onBeforeRenderObserver) {
  84818. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  84819. }
  84820. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  84821. },
  84822. enumerable: true,
  84823. configurable: true
  84824. });
  84825. Object.defineProperty(Layer.prototype, "onAfterRender", {
  84826. set: function (callback) {
  84827. if (this._onAfterRenderObserver) {
  84828. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  84829. }
  84830. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  84831. },
  84832. enumerable: true,
  84833. configurable: true
  84834. });
  84835. Layer.prototype._createIndexBuffer = function () {
  84836. var engine = this._scene.getEngine();
  84837. // Indices
  84838. var indices = [];
  84839. indices.push(0);
  84840. indices.push(1);
  84841. indices.push(2);
  84842. indices.push(0);
  84843. indices.push(2);
  84844. indices.push(3);
  84845. this._indexBuffer = engine.createIndexBuffer(indices);
  84846. };
  84847. Layer.prototype._rebuild = function () {
  84848. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84849. if (vb) {
  84850. vb._rebuild();
  84851. }
  84852. this._createIndexBuffer();
  84853. };
  84854. Layer.prototype.render = function () {
  84855. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  84856. // Check
  84857. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  84858. return;
  84859. var engine = this._scene.getEngine();
  84860. this.onBeforeRenderObservable.notifyObservers(this);
  84861. // Render
  84862. engine.enableEffect(currentEffect);
  84863. engine.setState(false);
  84864. // Texture
  84865. currentEffect.setTexture("textureSampler", this.texture);
  84866. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  84867. // Color
  84868. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  84869. // Scale / offset
  84870. currentEffect.setVector2("offset", this.offset);
  84871. currentEffect.setVector2("scale", this.scale);
  84872. // VBOs
  84873. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84874. // Draw order
  84875. if (!this.alphaTest) {
  84876. engine.setAlphaMode(this.alphaBlendingMode);
  84877. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84878. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84879. }
  84880. else {
  84881. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84882. }
  84883. this.onAfterRenderObservable.notifyObservers(this);
  84884. };
  84885. Layer.prototype.dispose = function () {
  84886. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84887. if (vertexBuffer) {
  84888. vertexBuffer.dispose();
  84889. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84890. }
  84891. if (this._indexBuffer) {
  84892. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84893. this._indexBuffer = null;
  84894. }
  84895. if (this.texture) {
  84896. this.texture.dispose();
  84897. this.texture = null;
  84898. }
  84899. // Remove from scene
  84900. var index = this._scene.layers.indexOf(this);
  84901. this._scene.layers.splice(index, 1);
  84902. // Callback
  84903. this.onDisposeObservable.notifyObservers(this);
  84904. this.onDisposeObservable.clear();
  84905. this.onAfterRenderObservable.clear();
  84906. this.onBeforeRenderObservable.clear();
  84907. };
  84908. return Layer;
  84909. }());
  84910. BABYLON.Layer = Layer;
  84911. })(BABYLON || (BABYLON = {}));
  84912. //# sourceMappingURL=babylon.layer.js.map
  84913. var BABYLON;
  84914. (function (BABYLON) {
  84915. var TextureTools = /** @class */ (function () {
  84916. function TextureTools() {
  84917. }
  84918. /**
  84919. * Uses the GPU to create a copy texture rescaled at a given size
  84920. * @param texture Texture to copy from
  84921. * @param width Desired width
  84922. * @param height Desired height
  84923. * @return Generated texture
  84924. */
  84925. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  84926. if (useBilinearMode === void 0) { useBilinearMode = true; }
  84927. var scene = texture.getScene();
  84928. var engine = scene.getEngine();
  84929. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  84930. rtt.wrapU = texture.wrapU;
  84931. rtt.wrapV = texture.wrapV;
  84932. rtt.uOffset = texture.uOffset;
  84933. rtt.vOffset = texture.vOffset;
  84934. rtt.uScale = texture.uScale;
  84935. rtt.vScale = texture.vScale;
  84936. rtt.uAng = texture.uAng;
  84937. rtt.vAng = texture.vAng;
  84938. rtt.wAng = texture.wAng;
  84939. rtt.coordinatesIndex = texture.coordinatesIndex;
  84940. rtt.level = texture.level;
  84941. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  84942. rtt._texture.isReady = false;
  84943. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84944. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84945. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84946. passPostProcess.getEffect().executeWhenCompiled(function () {
  84947. passPostProcess.onApply = function (effect) {
  84948. effect.setTexture("textureSampler", texture);
  84949. };
  84950. var internalTexture = rtt.getInternalTexture();
  84951. if (internalTexture) {
  84952. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  84953. engine.unBindFramebuffer(internalTexture);
  84954. rtt.disposeFramebufferObjects();
  84955. passPostProcess.dispose();
  84956. internalTexture.isReady = true;
  84957. }
  84958. });
  84959. return rtt;
  84960. };
  84961. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  84962. if (!scene._environmentBRDFTexture) {
  84963. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84964. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84965. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84966. scene._environmentBRDFTexture = texture;
  84967. }
  84968. return scene._environmentBRDFTexture;
  84969. };
  84970. 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=";
  84971. return TextureTools;
  84972. }());
  84973. BABYLON.TextureTools = TextureTools;
  84974. })(BABYLON || (BABYLON = {}));
  84975. //# sourceMappingURL=babylon.textureTools.js.map
  84976. var BABYLON;
  84977. (function (BABYLON) {
  84978. var FramingBehavior = /** @class */ (function () {
  84979. function FramingBehavior() {
  84980. this._mode = FramingBehavior.FitFrustumSidesMode;
  84981. this._radiusScale = 1.0;
  84982. this._positionScale = 0.5;
  84983. this._defaultElevation = 0.3;
  84984. this._elevationReturnTime = 1500;
  84985. this._elevationReturnWaitTime = 1000;
  84986. this._zoomStopsAnimation = false;
  84987. this._framingTime = 1500;
  84988. this._isPointerDown = false;
  84989. this._lastInteractionTime = -Infinity;
  84990. // Framing control
  84991. this._animatables = new Array();
  84992. this._betaIsAnimating = false;
  84993. }
  84994. Object.defineProperty(FramingBehavior.prototype, "name", {
  84995. get: function () {
  84996. return "Framing";
  84997. },
  84998. enumerable: true,
  84999. configurable: true
  85000. });
  85001. Object.defineProperty(FramingBehavior.prototype, "mode", {
  85002. /**
  85003. * Gets current mode used by the behavior.
  85004. */
  85005. get: function () {
  85006. return this._mode;
  85007. },
  85008. /**
  85009. * Sets the current mode used by the behavior
  85010. */
  85011. set: function (mode) {
  85012. this._mode = mode;
  85013. },
  85014. enumerable: true,
  85015. configurable: true
  85016. });
  85017. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  85018. /**
  85019. * Gets the scale applied to the radius
  85020. */
  85021. get: function () {
  85022. return this._radiusScale;
  85023. },
  85024. /**
  85025. * Sets the scale applied to the radius (1 by default)
  85026. */
  85027. set: function (radius) {
  85028. this._radiusScale = radius;
  85029. },
  85030. enumerable: true,
  85031. configurable: true
  85032. });
  85033. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  85034. /**
  85035. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  85036. */
  85037. get: function () {
  85038. return this._positionScale;
  85039. },
  85040. /**
  85041. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  85042. */
  85043. set: function (scale) {
  85044. this._positionScale = scale;
  85045. },
  85046. enumerable: true,
  85047. configurable: true
  85048. });
  85049. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  85050. /**
  85051. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  85052. * behaviour is triggered, in radians.
  85053. */
  85054. get: function () {
  85055. return this._defaultElevation;
  85056. },
  85057. /**
  85058. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  85059. * behaviour is triggered, in radians.
  85060. */
  85061. set: function (elevation) {
  85062. this._defaultElevation = elevation;
  85063. },
  85064. enumerable: true,
  85065. configurable: true
  85066. });
  85067. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  85068. /**
  85069. * Gets the time (in milliseconds) taken to return to the default beta position.
  85070. * Negative value indicates camera should not return to default.
  85071. */
  85072. get: function () {
  85073. return this._elevationReturnTime;
  85074. },
  85075. /**
  85076. * Sets the time (in milliseconds) taken to return to the default beta position.
  85077. * Negative value indicates camera should not return to default.
  85078. */
  85079. set: function (speed) {
  85080. this._elevationReturnTime = speed;
  85081. },
  85082. enumerable: true,
  85083. configurable: true
  85084. });
  85085. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  85086. /**
  85087. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  85088. */
  85089. get: function () {
  85090. return this._elevationReturnWaitTime;
  85091. },
  85092. /**
  85093. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  85094. */
  85095. set: function (time) {
  85096. this._elevationReturnWaitTime = time;
  85097. },
  85098. enumerable: true,
  85099. configurable: true
  85100. });
  85101. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  85102. /**
  85103. * Gets the flag that indicates if user zooming should stop animation.
  85104. */
  85105. get: function () {
  85106. return this._zoomStopsAnimation;
  85107. },
  85108. /**
  85109. * Sets the flag that indicates if user zooming should stop animation.
  85110. */
  85111. set: function (flag) {
  85112. this._zoomStopsAnimation = flag;
  85113. },
  85114. enumerable: true,
  85115. configurable: true
  85116. });
  85117. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  85118. /**
  85119. * Gets the transition time when framing the mesh, in milliseconds
  85120. */
  85121. get: function () {
  85122. return this._framingTime;
  85123. },
  85124. /**
  85125. * Sets the transition time when framing the mesh, in milliseconds
  85126. */
  85127. set: function (time) {
  85128. this._framingTime = time;
  85129. },
  85130. enumerable: true,
  85131. configurable: true
  85132. });
  85133. FramingBehavior.prototype.init = function () {
  85134. // Do notihng
  85135. };
  85136. FramingBehavior.prototype.attach = function (camera) {
  85137. var _this = this;
  85138. this._attachedCamera = camera;
  85139. var scene = this._attachedCamera.getScene();
  85140. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  85141. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85142. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85143. _this._isPointerDown = true;
  85144. return;
  85145. }
  85146. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85147. _this._isPointerDown = false;
  85148. }
  85149. });
  85150. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85151. if (mesh) {
  85152. _this.zoomOnMesh(mesh);
  85153. }
  85154. });
  85155. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85156. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85157. _this._applyUserInteraction();
  85158. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  85159. // back to the default position after a given timeout
  85160. _this._maintainCameraAboveGround();
  85161. });
  85162. };
  85163. FramingBehavior.prototype.detach = function () {
  85164. if (!this._attachedCamera) {
  85165. return;
  85166. }
  85167. var scene = this._attachedCamera.getScene();
  85168. if (this._onPrePointerObservableObserver) {
  85169. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85170. }
  85171. if (this._onAfterCheckInputsObserver) {
  85172. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85173. }
  85174. if (this._onMeshTargetChangedObserver) {
  85175. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85176. }
  85177. this._attachedCamera = null;
  85178. };
  85179. /**
  85180. * Targets the given mesh and updates zoom level accordingly.
  85181. * @param mesh The mesh to target.
  85182. * @param radius Optional. If a cached radius position already exists, overrides default.
  85183. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85184. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85185. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85186. */
  85187. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85188. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85189. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85190. mesh.computeWorldMatrix(true);
  85191. var boundingBox = mesh.getBoundingInfo().boundingBox;
  85192. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  85193. };
  85194. /**
  85195. * Targets the given mesh with its children and updates zoom level accordingly.
  85196. * @param mesh The mesh to target.
  85197. * @param radius Optional. If a cached radius position already exists, overrides default.
  85198. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85199. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85200. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85201. */
  85202. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85203. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85204. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85205. mesh.computeWorldMatrix(true);
  85206. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  85207. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  85208. };
  85209. /**
  85210. * Targets the given meshes with their children and updates zoom level accordingly.
  85211. * @param meshes The mesh to target.
  85212. * @param radius Optional. If a cached radius position already exists, overrides default.
  85213. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85214. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85215. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85216. */
  85217. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  85218. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85219. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85220. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  85221. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  85222. for (var i = 0; i < meshes.length; i++) {
  85223. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  85224. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  85225. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  85226. }
  85227. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  85228. };
  85229. /**
  85230. * Targets the given mesh and updates zoom level accordingly.
  85231. * @param mesh The mesh to target.
  85232. * @param radius Optional. If a cached radius position already exists, overrides default.
  85233. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85234. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85235. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85236. */
  85237. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  85238. var _this = this;
  85239. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85240. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85241. var zoomTarget;
  85242. if (!this._attachedCamera) {
  85243. return;
  85244. }
  85245. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  85246. var bottom = minimumWorld.y;
  85247. var top = maximumWorld.y;
  85248. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  85249. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  85250. if (focusOnOriginXZ) {
  85251. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  85252. }
  85253. else {
  85254. var centerWorld = minimumWorld.add(radiusWorld);
  85255. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  85256. }
  85257. if (!this._vectorTransition) {
  85258. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  85259. }
  85260. this._betaIsAnimating = true;
  85261. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  85262. if (animatable) {
  85263. this._animatables.push(animatable);
  85264. }
  85265. // sets the radius and lower radius bounds
  85266. // Small delta ensures camera is not always at lower zoom limit.
  85267. var radius = 0;
  85268. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  85269. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85270. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  85271. radius = position;
  85272. }
  85273. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85274. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85275. if (this._attachedCamera.lowerRadiusLimit === null) {
  85276. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  85277. }
  85278. }
  85279. // Set sensibilities
  85280. var extend = maximumWorld.subtract(minimumWorld).length();
  85281. this._attachedCamera.panningSensibility = 5000 / extend;
  85282. this._attachedCamera.wheelPrecision = 100 / radius;
  85283. // transition to new radius
  85284. if (!this._radiusTransition) {
  85285. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85286. }
  85287. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  85288. if (onAnimationEnd) {
  85289. onAnimationEnd();
  85290. }
  85291. if (_this._attachedCamera) {
  85292. _this._attachedCamera.storeState();
  85293. }
  85294. });
  85295. if (animatable) {
  85296. this._animatables.push(animatable);
  85297. }
  85298. };
  85299. /**
  85300. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  85301. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  85302. * frustum width.
  85303. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  85304. * to fully enclose the mesh in the viewing frustum.
  85305. */
  85306. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  85307. var size = maximumWorld.subtract(minimumWorld);
  85308. var boxVectorGlobalDiagonal = size.length();
  85309. var frustumSlope = this._getFrustumSlope();
  85310. // Formula for setting distance
  85311. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  85312. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  85313. // Horizon distance
  85314. var radius = radiusWithoutFraming * this._radiusScale;
  85315. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  85316. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  85317. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  85318. var camera = this._attachedCamera;
  85319. if (!camera) {
  85320. return 0;
  85321. }
  85322. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85323. // Don't exceed the requested limit
  85324. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  85325. }
  85326. // Don't exceed the upper radius limit
  85327. if (camera.upperRadiusLimit) {
  85328. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  85329. }
  85330. return distance;
  85331. };
  85332. /**
  85333. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  85334. * is automatically returned to its default position (expected to be above ground plane).
  85335. */
  85336. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  85337. var _this = this;
  85338. if (this._elevationReturnTime < 0) {
  85339. return;
  85340. }
  85341. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  85342. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  85343. var limitBeta = Math.PI * 0.5;
  85344. // Bring the camera back up if below the ground plane
  85345. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  85346. this._betaIsAnimating = true;
  85347. //Transition to new position
  85348. this.stopAllAnimations();
  85349. if (!this._betaTransition) {
  85350. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85351. }
  85352. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  85353. _this._clearAnimationLocks();
  85354. _this.stopAllAnimations();
  85355. });
  85356. if (animatabe) {
  85357. this._animatables.push(animatabe);
  85358. }
  85359. }
  85360. };
  85361. /**
  85362. * Returns the frustum slope based on the canvas ratio and camera FOV
  85363. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  85364. */
  85365. FramingBehavior.prototype._getFrustumSlope = function () {
  85366. // Calculate the viewport ratio
  85367. // Aspect Ratio is Height/Width.
  85368. var camera = this._attachedCamera;
  85369. if (!camera) {
  85370. return BABYLON.Vector2.Zero();
  85371. }
  85372. var engine = camera.getScene().getEngine();
  85373. var aspectRatio = engine.getAspectRatio(camera);
  85374. // Camera FOV is the vertical field of view (top-bottom) in radians.
  85375. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  85376. var frustumSlopeY = Math.tan(camera.fov / 2);
  85377. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  85378. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  85379. // along the forward vector.
  85380. var frustumSlopeX = frustumSlopeY * aspectRatio;
  85381. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  85382. };
  85383. /**
  85384. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  85385. */
  85386. FramingBehavior.prototype._clearAnimationLocks = function () {
  85387. this._betaIsAnimating = false;
  85388. };
  85389. /**
  85390. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85391. */
  85392. FramingBehavior.prototype._applyUserInteraction = function () {
  85393. if (this.isUserIsMoving) {
  85394. this._lastInteractionTime = BABYLON.Tools.Now;
  85395. this.stopAllAnimations();
  85396. this._clearAnimationLocks();
  85397. }
  85398. };
  85399. /**
  85400. * Stops and removes all animations that have been applied to the camera
  85401. */
  85402. FramingBehavior.prototype.stopAllAnimations = function () {
  85403. if (this._attachedCamera) {
  85404. this._attachedCamera.animations = [];
  85405. }
  85406. while (this._animatables.length) {
  85407. if (this._animatables[0]) {
  85408. this._animatables[0].onAnimationEnd = null;
  85409. this._animatables[0].stop();
  85410. }
  85411. this._animatables.shift();
  85412. }
  85413. };
  85414. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  85415. /**
  85416. * Gets a value indicating if the user is moving the camera
  85417. */
  85418. get: function () {
  85419. if (!this._attachedCamera) {
  85420. return false;
  85421. }
  85422. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85423. this._attachedCamera.inertialBetaOffset !== 0 ||
  85424. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85425. this._attachedCamera.inertialPanningX !== 0 ||
  85426. this._attachedCamera.inertialPanningY !== 0 ||
  85427. this._isPointerDown;
  85428. },
  85429. enumerable: true,
  85430. configurable: true
  85431. });
  85432. /**
  85433. * The easing function used by animations
  85434. */
  85435. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  85436. /**
  85437. * The easing mode used by animations
  85438. */
  85439. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  85440. // Statics
  85441. /**
  85442. * The camera can move all the way towards the mesh.
  85443. */
  85444. FramingBehavior.IgnoreBoundsSizeMode = 0;
  85445. /**
  85446. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  85447. */
  85448. FramingBehavior.FitFrustumSidesMode = 1;
  85449. return FramingBehavior;
  85450. }());
  85451. BABYLON.FramingBehavior = FramingBehavior;
  85452. })(BABYLON || (BABYLON = {}));
  85453. //# sourceMappingURL=babylon.framingBehavior.js.map
  85454. var BABYLON;
  85455. (function (BABYLON) {
  85456. /**
  85457. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  85458. */
  85459. var BouncingBehavior = /** @class */ (function () {
  85460. function BouncingBehavior() {
  85461. /**
  85462. * The duration of the animation, in milliseconds
  85463. */
  85464. this.transitionDuration = 450;
  85465. /**
  85466. * Length of the distance animated by the transition when lower radius is reached
  85467. */
  85468. this.lowerRadiusTransitionRange = 2;
  85469. /**
  85470. * Length of the distance animated by the transition when upper radius is reached
  85471. */
  85472. this.upperRadiusTransitionRange = -2;
  85473. this._autoTransitionRange = false;
  85474. // Animations
  85475. this._radiusIsAnimating = false;
  85476. this._radiusBounceTransition = null;
  85477. this._animatables = new Array();
  85478. }
  85479. Object.defineProperty(BouncingBehavior.prototype, "name", {
  85480. get: function () {
  85481. return "Bouncing";
  85482. },
  85483. enumerable: true,
  85484. configurable: true
  85485. });
  85486. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  85487. /**
  85488. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85489. */
  85490. get: function () {
  85491. return this._autoTransitionRange;
  85492. },
  85493. /**
  85494. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85495. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  85496. */
  85497. set: function (value) {
  85498. var _this = this;
  85499. if (this._autoTransitionRange === value) {
  85500. return;
  85501. }
  85502. this._autoTransitionRange = value;
  85503. var camera = this._attachedCamera;
  85504. if (!camera) {
  85505. return;
  85506. }
  85507. if (value) {
  85508. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85509. if (!mesh) {
  85510. return;
  85511. }
  85512. mesh.computeWorldMatrix(true);
  85513. var diagonal = mesh.getBoundingInfo().diagonalLength;
  85514. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  85515. _this.upperRadiusTransitionRange = diagonal * 0.05;
  85516. });
  85517. }
  85518. else if (this._onMeshTargetChangedObserver) {
  85519. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85520. }
  85521. },
  85522. enumerable: true,
  85523. configurable: true
  85524. });
  85525. BouncingBehavior.prototype.init = function () {
  85526. // Do notihng
  85527. };
  85528. BouncingBehavior.prototype.attach = function (camera) {
  85529. var _this = this;
  85530. this._attachedCamera = camera;
  85531. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85532. if (!_this._attachedCamera) {
  85533. return;
  85534. }
  85535. // Add the bounce animation to the lower radius limit
  85536. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  85537. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  85538. }
  85539. // Add the bounce animation to the upper radius limit
  85540. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  85541. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  85542. }
  85543. });
  85544. };
  85545. BouncingBehavior.prototype.detach = function () {
  85546. if (!this._attachedCamera) {
  85547. return;
  85548. }
  85549. if (this._onAfterCheckInputsObserver) {
  85550. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85551. }
  85552. if (this._onMeshTargetChangedObserver) {
  85553. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85554. }
  85555. this._attachedCamera = null;
  85556. };
  85557. /**
  85558. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  85559. * @param radiusLimit The limit to check against.
  85560. * @return Bool to indicate if at limit.
  85561. */
  85562. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  85563. if (!this._attachedCamera) {
  85564. return false;
  85565. }
  85566. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  85567. return true;
  85568. }
  85569. return false;
  85570. };
  85571. /**
  85572. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  85573. * @param radiusDelta The delta by which to animate to. Can be negative.
  85574. */
  85575. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  85576. var _this = this;
  85577. if (!this._attachedCamera) {
  85578. return;
  85579. }
  85580. if (!this._radiusBounceTransition) {
  85581. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  85582. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  85583. }
  85584. // Prevent zoom until bounce has completed
  85585. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  85586. this._attachedCamera.wheelPrecision = Infinity;
  85587. this._attachedCamera.inertialRadiusOffset = 0;
  85588. // Animate to the radius limit
  85589. this.stopAllAnimations();
  85590. this._radiusIsAnimating = true;
  85591. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  85592. if (animatable) {
  85593. this._animatables.push(animatable);
  85594. }
  85595. };
  85596. /**
  85597. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  85598. */
  85599. BouncingBehavior.prototype._clearAnimationLocks = function () {
  85600. this._radiusIsAnimating = false;
  85601. if (this._attachedCamera) {
  85602. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  85603. }
  85604. };
  85605. /**
  85606. * Stops and removes all animations that have been applied to the camera
  85607. */
  85608. BouncingBehavior.prototype.stopAllAnimations = function () {
  85609. if (this._attachedCamera) {
  85610. this._attachedCamera.animations = [];
  85611. }
  85612. while (this._animatables.length) {
  85613. this._animatables[0].onAnimationEnd = null;
  85614. this._animatables[0].stop();
  85615. this._animatables.shift();
  85616. }
  85617. };
  85618. /**
  85619. * The easing function used by animations
  85620. */
  85621. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  85622. /**
  85623. * The easing mode used by animations
  85624. */
  85625. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  85626. return BouncingBehavior;
  85627. }());
  85628. BABYLON.BouncingBehavior = BouncingBehavior;
  85629. })(BABYLON || (BABYLON = {}));
  85630. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  85631. var BABYLON;
  85632. (function (BABYLON) {
  85633. var AutoRotationBehavior = /** @class */ (function () {
  85634. function AutoRotationBehavior() {
  85635. this._zoomStopsAnimation = false;
  85636. this._idleRotationSpeed = 0.05;
  85637. this._idleRotationWaitTime = 2000;
  85638. this._idleRotationSpinupTime = 2000;
  85639. this._isPointerDown = false;
  85640. this._lastFrameTime = null;
  85641. this._lastInteractionTime = -Infinity;
  85642. this._cameraRotationSpeed = 0;
  85643. this._lastFrameRadius = 0;
  85644. }
  85645. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  85646. get: function () {
  85647. return "AutoRotation";
  85648. },
  85649. enumerable: true,
  85650. configurable: true
  85651. });
  85652. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  85653. /**
  85654. * Gets the flag that indicates if user zooming should stop animation.
  85655. */
  85656. get: function () {
  85657. return this._zoomStopsAnimation;
  85658. },
  85659. /**
  85660. * Sets the flag that indicates if user zooming should stop animation.
  85661. */
  85662. set: function (flag) {
  85663. this._zoomStopsAnimation = flag;
  85664. },
  85665. enumerable: true,
  85666. configurable: true
  85667. });
  85668. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  85669. /**
  85670. * Gets the default speed at which the camera rotates around the model.
  85671. */
  85672. get: function () {
  85673. return this._idleRotationSpeed;
  85674. },
  85675. /**
  85676. * Sets the default speed at which the camera rotates around the model.
  85677. */
  85678. set: function (speed) {
  85679. this._idleRotationSpeed = speed;
  85680. },
  85681. enumerable: true,
  85682. configurable: true
  85683. });
  85684. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  85685. /**
  85686. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  85687. */
  85688. get: function () {
  85689. return this._idleRotationWaitTime;
  85690. },
  85691. /**
  85692. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  85693. */
  85694. set: function (time) {
  85695. this._idleRotationWaitTime = time;
  85696. },
  85697. enumerable: true,
  85698. configurable: true
  85699. });
  85700. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  85701. /**
  85702. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85703. */
  85704. get: function () {
  85705. return this._idleRotationSpinupTime;
  85706. },
  85707. /**
  85708. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85709. */
  85710. set: function (time) {
  85711. this._idleRotationSpinupTime = time;
  85712. },
  85713. enumerable: true,
  85714. configurable: true
  85715. });
  85716. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  85717. /**
  85718. * Gets a value indicating if the camera is currently rotating because of this behavior
  85719. */
  85720. get: function () {
  85721. return Math.abs(this._cameraRotationSpeed) > 0;
  85722. },
  85723. enumerable: true,
  85724. configurable: true
  85725. });
  85726. AutoRotationBehavior.prototype.init = function () {
  85727. // Do notihng
  85728. };
  85729. AutoRotationBehavior.prototype.attach = function (camera) {
  85730. var _this = this;
  85731. this._attachedCamera = camera;
  85732. var scene = this._attachedCamera.getScene();
  85733. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85734. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85735. _this._isPointerDown = true;
  85736. return;
  85737. }
  85738. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85739. _this._isPointerDown = false;
  85740. }
  85741. });
  85742. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85743. var now = BABYLON.Tools.Now;
  85744. var dt = 0;
  85745. if (_this._lastFrameTime != null) {
  85746. dt = now - _this._lastFrameTime;
  85747. }
  85748. _this._lastFrameTime = now;
  85749. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85750. _this._applyUserInteraction();
  85751. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  85752. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  85753. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  85754. // Step camera rotation by rotation speed
  85755. if (_this._attachedCamera) {
  85756. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  85757. }
  85758. });
  85759. };
  85760. AutoRotationBehavior.prototype.detach = function () {
  85761. if (!this._attachedCamera) {
  85762. return;
  85763. }
  85764. var scene = this._attachedCamera.getScene();
  85765. if (this._onPrePointerObservableObserver) {
  85766. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85767. }
  85768. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85769. this._attachedCamera = null;
  85770. };
  85771. /**
  85772. * Returns true if user is scrolling.
  85773. * @return true if user is scrolling.
  85774. */
  85775. AutoRotationBehavior.prototype._userIsZooming = function () {
  85776. if (!this._attachedCamera) {
  85777. return false;
  85778. }
  85779. return this._attachedCamera.inertialRadiusOffset !== 0;
  85780. };
  85781. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  85782. if (!this._attachedCamera) {
  85783. return false;
  85784. }
  85785. var zoomHasHitLimit = false;
  85786. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  85787. zoomHasHitLimit = true;
  85788. }
  85789. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  85790. this._lastFrameRadius = this._attachedCamera.radius;
  85791. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  85792. };
  85793. /**
  85794. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85795. */
  85796. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  85797. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  85798. this._lastInteractionTime = BABYLON.Tools.Now;
  85799. }
  85800. };
  85801. // Tools
  85802. AutoRotationBehavior.prototype._userIsMoving = function () {
  85803. if (!this._attachedCamera) {
  85804. return false;
  85805. }
  85806. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85807. this._attachedCamera.inertialBetaOffset !== 0 ||
  85808. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85809. this._attachedCamera.inertialPanningX !== 0 ||
  85810. this._attachedCamera.inertialPanningY !== 0 ||
  85811. this._isPointerDown;
  85812. };
  85813. return AutoRotationBehavior;
  85814. }());
  85815. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  85816. })(BABYLON || (BABYLON = {}));
  85817. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  85818. var BABYLON;
  85819. (function (BABYLON) {
  85820. var NullEngineOptions = /** @class */ (function () {
  85821. function NullEngineOptions() {
  85822. this.renderWidth = 512;
  85823. this.renderHeight = 256;
  85824. this.textureSize = 512;
  85825. this.deterministicLockstep = false;
  85826. this.lockstepMaxSteps = 4;
  85827. }
  85828. return NullEngineOptions;
  85829. }());
  85830. BABYLON.NullEngineOptions = NullEngineOptions;
  85831. /**
  85832. * The null engine class provides support for headless version of babylon.js.
  85833. * This can be used in server side scenario or for testing purposes
  85834. */
  85835. var NullEngine = /** @class */ (function (_super) {
  85836. __extends(NullEngine, _super);
  85837. function NullEngine(options) {
  85838. if (options === void 0) { options = new NullEngineOptions(); }
  85839. var _this = _super.call(this, null) || this;
  85840. if (options.deterministicLockstep === undefined) {
  85841. options.deterministicLockstep = false;
  85842. }
  85843. if (options.lockstepMaxSteps === undefined) {
  85844. options.lockstepMaxSteps = 4;
  85845. }
  85846. _this._options = options;
  85847. // Init caps
  85848. // We consider we are on a webgl1 capable device
  85849. _this._caps = new BABYLON.EngineCapabilities();
  85850. _this._caps.maxTexturesImageUnits = 16;
  85851. _this._caps.maxVertexTextureImageUnits = 16;
  85852. _this._caps.maxTextureSize = 512;
  85853. _this._caps.maxCubemapTextureSize = 512;
  85854. _this._caps.maxRenderTextureSize = 512;
  85855. _this._caps.maxVertexAttribs = 16;
  85856. _this._caps.maxVaryingVectors = 16;
  85857. _this._caps.maxFragmentUniformVectors = 16;
  85858. _this._caps.maxVertexUniformVectors = 16;
  85859. // Extensions
  85860. _this._caps.standardDerivatives = false;
  85861. _this._caps.astc = null;
  85862. _this._caps.s3tc = null;
  85863. _this._caps.pvrtc = null;
  85864. _this._caps.etc1 = null;
  85865. _this._caps.etc2 = null;
  85866. _this._caps.textureAnisotropicFilterExtension = null;
  85867. _this._caps.maxAnisotropy = 0;
  85868. _this._caps.uintIndices = false;
  85869. _this._caps.fragmentDepthSupported = false;
  85870. _this._caps.highPrecisionShaderSupported = true;
  85871. _this._caps.colorBufferFloat = false;
  85872. _this._caps.textureFloat = false;
  85873. _this._caps.textureFloatLinearFiltering = false;
  85874. _this._caps.textureFloatRender = false;
  85875. _this._caps.textureHalfFloat = false;
  85876. _this._caps.textureHalfFloatLinearFiltering = false;
  85877. _this._caps.textureHalfFloatRender = false;
  85878. _this._caps.textureLOD = false;
  85879. _this._caps.drawBuffersExtension = false;
  85880. _this._caps.depthTextureExtension = false;
  85881. _this._caps.vertexArrayObject = false;
  85882. _this._caps.instancedArrays = false;
  85883. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  85884. // Wrappers
  85885. if (typeof URL === "undefined") {
  85886. URL = {
  85887. createObjectURL: function () { },
  85888. revokeObjectURL: function () { }
  85889. };
  85890. }
  85891. if (typeof Blob === "undefined") {
  85892. Blob = function () { };
  85893. }
  85894. return _this;
  85895. }
  85896. NullEngine.prototype.isDeterministicLockStep = function () {
  85897. return this._options.deterministicLockstep;
  85898. };
  85899. NullEngine.prototype.getLockstepMaxSteps = function () {
  85900. return this._options.lockstepMaxSteps;
  85901. };
  85902. NullEngine.prototype.createVertexBuffer = function (vertices) {
  85903. return {
  85904. capacity: 0,
  85905. references: 1,
  85906. is32Bits: false
  85907. };
  85908. };
  85909. NullEngine.prototype.createIndexBuffer = function (indices) {
  85910. return {
  85911. capacity: 0,
  85912. references: 1,
  85913. is32Bits: false
  85914. };
  85915. };
  85916. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  85917. if (stencil === void 0) { stencil = false; }
  85918. };
  85919. NullEngine.prototype.getRenderWidth = function (useScreen) {
  85920. if (useScreen === void 0) { useScreen = false; }
  85921. if (!useScreen && this._currentRenderTarget) {
  85922. return this._currentRenderTarget.width;
  85923. }
  85924. return this._options.renderWidth;
  85925. };
  85926. NullEngine.prototype.getRenderHeight = function (useScreen) {
  85927. if (useScreen === void 0) { useScreen = false; }
  85928. if (!useScreen && this._currentRenderTarget) {
  85929. return this._currentRenderTarget.height;
  85930. }
  85931. return this._options.renderHeight;
  85932. };
  85933. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  85934. this._cachedViewport = viewport;
  85935. };
  85936. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  85937. return {
  85938. transformFeedback: null,
  85939. __SPECTOR_rebuildProgram: null
  85940. };
  85941. };
  85942. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  85943. return [];
  85944. };
  85945. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  85946. return [];
  85947. };
  85948. NullEngine.prototype.bindSamplers = function (effect) {
  85949. this._currentEffect = null;
  85950. };
  85951. NullEngine.prototype.enableEffect = function (effect) {
  85952. this._currentEffect = effect;
  85953. if (effect.onBind) {
  85954. effect.onBind(effect);
  85955. }
  85956. effect.onBindObservable.notifyObservers(effect);
  85957. };
  85958. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  85959. if (zOffset === void 0) { zOffset = 0; }
  85960. if (reverseSide === void 0) { reverseSide = false; }
  85961. };
  85962. NullEngine.prototype.setIntArray = function (uniform, array) {
  85963. };
  85964. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  85965. };
  85966. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  85967. };
  85968. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  85969. };
  85970. NullEngine.prototype.setFloatArray = function (uniform, array) {
  85971. };
  85972. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  85973. };
  85974. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  85975. };
  85976. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  85977. };
  85978. NullEngine.prototype.setArray = function (uniform, array) {
  85979. };
  85980. NullEngine.prototype.setArray2 = function (uniform, array) {
  85981. };
  85982. NullEngine.prototype.setArray3 = function (uniform, array) {
  85983. };
  85984. NullEngine.prototype.setArray4 = function (uniform, array) {
  85985. };
  85986. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  85987. };
  85988. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  85989. };
  85990. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  85991. };
  85992. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  85993. };
  85994. NullEngine.prototype.setFloat = function (uniform, value) {
  85995. };
  85996. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  85997. };
  85998. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  85999. };
  86000. NullEngine.prototype.setBool = function (uniform, bool) {
  86001. };
  86002. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  86003. };
  86004. NullEngine.prototype.setColor3 = function (uniform, color3) {
  86005. };
  86006. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  86007. };
  86008. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  86009. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  86010. if (this._alphaMode === mode) {
  86011. return;
  86012. }
  86013. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  86014. if (!noDepthWriteChange) {
  86015. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  86016. }
  86017. this._alphaMode = mode;
  86018. };
  86019. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  86020. };
  86021. NullEngine.prototype.wipeCaches = function (bruteForce) {
  86022. if (this.preventCacheWipeBetweenFrames) {
  86023. return;
  86024. }
  86025. this.resetTextureCache();
  86026. this._currentEffect = null;
  86027. if (bruteForce) {
  86028. this._currentProgram = null;
  86029. this._stencilState.reset();
  86030. this._depthCullingState.reset();
  86031. this.setDepthFunctionToLessOrEqual();
  86032. this._alphaState.reset();
  86033. }
  86034. this._cachedVertexBuffers = null;
  86035. this._cachedIndexBuffer = null;
  86036. this._cachedEffectForVertexBuffers = null;
  86037. };
  86038. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  86039. };
  86040. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  86041. };
  86042. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  86043. };
  86044. NullEngine.prototype._createTexture = function () {
  86045. return {};
  86046. };
  86047. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  86048. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86049. if (onLoad === void 0) { onLoad = null; }
  86050. if (onError === void 0) { onError = null; }
  86051. if (buffer === void 0) { buffer = null; }
  86052. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  86053. var url = String(urlArg);
  86054. texture.url = url;
  86055. texture.generateMipMaps = !noMipmap;
  86056. texture.samplingMode = samplingMode;
  86057. texture.invertY = invertY;
  86058. texture.baseWidth = this._options.textureSize;
  86059. texture.baseHeight = this._options.textureSize;
  86060. texture.width = this._options.textureSize;
  86061. texture.height = this._options.textureSize;
  86062. if (format) {
  86063. texture.format = format;
  86064. }
  86065. texture.isReady = true;
  86066. if (onLoad) {
  86067. onLoad();
  86068. }
  86069. return texture;
  86070. };
  86071. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  86072. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  86073. if (options !== undefined && typeof options === "object") {
  86074. fullOptions.generateMipMaps = options.generateMipMaps;
  86075. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  86076. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  86077. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  86078. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  86079. }
  86080. else {
  86081. fullOptions.generateMipMaps = options;
  86082. fullOptions.generateDepthBuffer = true;
  86083. fullOptions.generateStencilBuffer = false;
  86084. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86085. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  86086. }
  86087. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  86088. var width = size.width || size;
  86089. var height = size.height || size;
  86090. texture._depthStencilBuffer = {};
  86091. texture._framebuffer = {};
  86092. texture.baseWidth = width;
  86093. texture.baseHeight = height;
  86094. texture.width = width;
  86095. texture.height = height;
  86096. texture.isReady = true;
  86097. texture.samples = 1;
  86098. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  86099. texture.samplingMode = fullOptions.samplingMode;
  86100. texture.type = fullOptions.type;
  86101. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  86102. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  86103. return texture;
  86104. };
  86105. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  86106. texture.samplingMode = samplingMode;
  86107. };
  86108. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  86109. if (this._currentRenderTarget) {
  86110. this.unBindFramebuffer(this._currentRenderTarget);
  86111. }
  86112. this._currentRenderTarget = texture;
  86113. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  86114. if (this._cachedViewport && !forceFullscreenViewport) {
  86115. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  86116. }
  86117. };
  86118. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  86119. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  86120. this._currentRenderTarget = null;
  86121. if (onBeforeUnbind) {
  86122. if (texture._MSAAFramebuffer) {
  86123. this._currentFramebuffer = texture._framebuffer;
  86124. }
  86125. onBeforeUnbind();
  86126. }
  86127. this._currentFramebuffer = null;
  86128. };
  86129. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  86130. var vbo = {
  86131. capacity: 1,
  86132. references: 1,
  86133. is32Bits: false
  86134. };
  86135. return vbo;
  86136. };
  86137. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  86138. if (offset === void 0) { offset = 0; }
  86139. };
  86140. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  86141. };
  86142. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  86143. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  86144. this._boundTexturesCache[this._activeChannel] = texture;
  86145. }
  86146. };
  86147. NullEngine.prototype._bindTexture = function (channel, texture) {
  86148. if (channel < 0) {
  86149. return;
  86150. }
  86151. this._bindTextureDirectly(0, texture);
  86152. };
  86153. NullEngine.prototype._releaseBuffer = function (buffer) {
  86154. buffer.references--;
  86155. if (buffer.references === 0) {
  86156. return true;
  86157. }
  86158. return false;
  86159. };
  86160. return NullEngine;
  86161. }(BABYLON.Engine));
  86162. BABYLON.NullEngine = NullEngine;
  86163. })(BABYLON || (BABYLON = {}));
  86164. //# sourceMappingURL=babylon.nullEngine.js.map
  86165. var BABYLON;
  86166. (function (BABYLON) {
  86167. /**
  86168. * This class can be used to get instrumentation data from a Babylon engine
  86169. */
  86170. var EngineInstrumentation = /** @class */ (function () {
  86171. function EngineInstrumentation(engine) {
  86172. this.engine = engine;
  86173. this._captureGPUFrameTime = false;
  86174. this._gpuFrameTime = new BABYLON.PerfCounter();
  86175. this._captureShaderCompilationTime = false;
  86176. this._shaderCompilationTime = new BABYLON.PerfCounter();
  86177. // Observers
  86178. this._onBeginFrameObserver = null;
  86179. this._onEndFrameObserver = null;
  86180. this._onBeforeShaderCompilationObserver = null;
  86181. this._onAfterShaderCompilationObserver = null;
  86182. }
  86183. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  86184. // Properties
  86185. /**
  86186. * Gets the perf counter used for GPU frame time
  86187. */
  86188. get: function () {
  86189. return this._gpuFrameTime;
  86190. },
  86191. enumerable: true,
  86192. configurable: true
  86193. });
  86194. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  86195. /**
  86196. * Gets the GPU frame time capture status
  86197. */
  86198. get: function () {
  86199. return this._captureGPUFrameTime;
  86200. },
  86201. /**
  86202. * Enable or disable the GPU frame time capture
  86203. */
  86204. set: function (value) {
  86205. var _this = this;
  86206. if (value === this._captureGPUFrameTime) {
  86207. return;
  86208. }
  86209. this._captureGPUFrameTime = value;
  86210. if (value) {
  86211. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  86212. if (!_this._gpuFrameTimeToken) {
  86213. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  86214. }
  86215. });
  86216. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  86217. if (!_this._gpuFrameTimeToken) {
  86218. return;
  86219. }
  86220. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  86221. if (time > -1) {
  86222. _this._gpuFrameTimeToken = null;
  86223. _this._gpuFrameTime.fetchNewFrame();
  86224. _this._gpuFrameTime.addCount(time, true);
  86225. }
  86226. });
  86227. }
  86228. else {
  86229. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  86230. this._onBeginFrameObserver = null;
  86231. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  86232. this._onEndFrameObserver = null;
  86233. }
  86234. },
  86235. enumerable: true,
  86236. configurable: true
  86237. });
  86238. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  86239. /**
  86240. * Gets the perf counter used for shader compilation time
  86241. */
  86242. get: function () {
  86243. return this._shaderCompilationTime;
  86244. },
  86245. enumerable: true,
  86246. configurable: true
  86247. });
  86248. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  86249. /**
  86250. * Gets the shader compilation time capture status
  86251. */
  86252. get: function () {
  86253. return this._captureShaderCompilationTime;
  86254. },
  86255. /**
  86256. * Enable or disable the shader compilation time capture
  86257. */
  86258. set: function (value) {
  86259. var _this = this;
  86260. if (value === this._captureShaderCompilationTime) {
  86261. return;
  86262. }
  86263. this._captureShaderCompilationTime = value;
  86264. if (value) {
  86265. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  86266. _this._shaderCompilationTime.fetchNewFrame();
  86267. _this._shaderCompilationTime.beginMonitoring();
  86268. });
  86269. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  86270. _this._shaderCompilationTime.endMonitoring();
  86271. });
  86272. }
  86273. else {
  86274. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  86275. this._onBeforeShaderCompilationObserver = null;
  86276. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  86277. this._onAfterShaderCompilationObserver = null;
  86278. }
  86279. },
  86280. enumerable: true,
  86281. configurable: true
  86282. });
  86283. EngineInstrumentation.prototype.dispose = function () {
  86284. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  86285. this._onBeginFrameObserver = null;
  86286. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  86287. this._onEndFrameObserver = null;
  86288. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  86289. this._onBeforeShaderCompilationObserver = null;
  86290. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  86291. this._onAfterShaderCompilationObserver = null;
  86292. this.engine = null;
  86293. };
  86294. return EngineInstrumentation;
  86295. }());
  86296. BABYLON.EngineInstrumentation = EngineInstrumentation;
  86297. })(BABYLON || (BABYLON = {}));
  86298. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  86299. var BABYLON;
  86300. (function (BABYLON) {
  86301. /**
  86302. * This class can be used to get instrumentation data from a Babylon engine
  86303. */
  86304. var SceneInstrumentation = /** @class */ (function () {
  86305. function SceneInstrumentation(scene) {
  86306. var _this = this;
  86307. this.scene = scene;
  86308. this._captureActiveMeshesEvaluationTime = false;
  86309. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  86310. this._captureRenderTargetsRenderTime = false;
  86311. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  86312. this._captureFrameTime = false;
  86313. this._frameTime = new BABYLON.PerfCounter();
  86314. this._captureRenderTime = false;
  86315. this._renderTime = new BABYLON.PerfCounter();
  86316. this._captureInterFrameTime = false;
  86317. this._interFrameTime = new BABYLON.PerfCounter();
  86318. this._captureParticlesRenderTime = false;
  86319. this._particlesRenderTime = new BABYLON.PerfCounter();
  86320. this._captureSpritesRenderTime = false;
  86321. this._spritesRenderTime = new BABYLON.PerfCounter();
  86322. this._capturePhysicsTime = false;
  86323. this._physicsTime = new BABYLON.PerfCounter();
  86324. this._captureAnimationsTime = false;
  86325. this._animationsTime = new BABYLON.PerfCounter();
  86326. // Observers
  86327. this._onBeforeActiveMeshesEvaluationObserver = null;
  86328. this._onAfterActiveMeshesEvaluationObserver = null;
  86329. this._onBeforeRenderTargetsRenderObserver = null;
  86330. this._onAfterRenderTargetsRenderObserver = null;
  86331. this._onAfterRenderObserver = null;
  86332. this._onBeforeDrawPhaseObserver = null;
  86333. this._onAfterDrawPhaseObserver = null;
  86334. this._onBeforeAnimationsObserver = null;
  86335. this._onBeforeParticlesRenderingObserver = null;
  86336. this._onAfterParticlesRenderingObserver = null;
  86337. this._onBeforeSpritesRenderingObserver = null;
  86338. this._onAfterSpritesRenderingObserver = null;
  86339. this._onBeforePhysicsObserver = null;
  86340. this._onAfterPhysicsObserver = null;
  86341. this._onAfterAnimationsObserver = null;
  86342. // Before render
  86343. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  86344. if (_this._captureActiveMeshesEvaluationTime) {
  86345. _this._activeMeshesEvaluationTime.fetchNewFrame();
  86346. }
  86347. if (_this._captureRenderTargetsRenderTime) {
  86348. _this._renderTargetsRenderTime.fetchNewFrame();
  86349. }
  86350. if (_this._captureFrameTime) {
  86351. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  86352. _this._frameTime.beginMonitoring();
  86353. }
  86354. if (_this._captureInterFrameTime) {
  86355. _this._interFrameTime.endMonitoring();
  86356. }
  86357. if (_this._captureParticlesRenderTime) {
  86358. _this._particlesRenderTime.fetchNewFrame();
  86359. }
  86360. if (_this._captureSpritesRenderTime) {
  86361. _this._spritesRenderTime.fetchNewFrame();
  86362. }
  86363. if (_this._captureAnimationsTime) {
  86364. _this._animationsTime.beginMonitoring();
  86365. }
  86366. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  86367. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  86368. });
  86369. // After render
  86370. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  86371. if (_this._captureFrameTime) {
  86372. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  86373. _this._frameTime.endMonitoring();
  86374. }
  86375. if (_this._captureRenderTime) {
  86376. _this._renderTime.endMonitoring(false);
  86377. }
  86378. if (_this._captureInterFrameTime) {
  86379. _this._interFrameTime.beginMonitoring();
  86380. }
  86381. });
  86382. }
  86383. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  86384. // Properties
  86385. /**
  86386. * Gets the perf counter used for active meshes evaluation time
  86387. */
  86388. get: function () {
  86389. return this._activeMeshesEvaluationTime;
  86390. },
  86391. enumerable: true,
  86392. configurable: true
  86393. });
  86394. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  86395. /**
  86396. * Gets the active meshes evaluation time capture status
  86397. */
  86398. get: function () {
  86399. return this._captureActiveMeshesEvaluationTime;
  86400. },
  86401. /**
  86402. * Enable or disable the active meshes evaluation time capture
  86403. */
  86404. set: function (value) {
  86405. var _this = this;
  86406. if (value === this._captureActiveMeshesEvaluationTime) {
  86407. return;
  86408. }
  86409. this._captureActiveMeshesEvaluationTime = value;
  86410. if (value) {
  86411. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  86412. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  86413. _this._activeMeshesEvaluationTime.beginMonitoring();
  86414. });
  86415. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  86416. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  86417. _this._activeMeshesEvaluationTime.endMonitoring();
  86418. });
  86419. }
  86420. else {
  86421. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86422. this._onBeforeActiveMeshesEvaluationObserver = null;
  86423. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86424. this._onAfterActiveMeshesEvaluationObserver = null;
  86425. }
  86426. },
  86427. enumerable: true,
  86428. configurable: true
  86429. });
  86430. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  86431. /**
  86432. * Gets the perf counter used for render targets render time
  86433. */
  86434. get: function () {
  86435. return this._renderTargetsRenderTime;
  86436. },
  86437. enumerable: true,
  86438. configurable: true
  86439. });
  86440. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  86441. /**
  86442. * Gets the render targets render time capture status
  86443. */
  86444. get: function () {
  86445. return this._captureRenderTargetsRenderTime;
  86446. },
  86447. /**
  86448. * Enable or disable the render targets render time capture
  86449. */
  86450. set: function (value) {
  86451. var _this = this;
  86452. if (value === this._captureRenderTargetsRenderTime) {
  86453. return;
  86454. }
  86455. this._captureRenderTargetsRenderTime = value;
  86456. if (value) {
  86457. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  86458. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  86459. _this._renderTargetsRenderTime.beginMonitoring();
  86460. });
  86461. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  86462. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  86463. _this._renderTargetsRenderTime.endMonitoring(false);
  86464. });
  86465. }
  86466. else {
  86467. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86468. this._onBeforeRenderTargetsRenderObserver = null;
  86469. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86470. this._onAfterRenderTargetsRenderObserver = null;
  86471. }
  86472. },
  86473. enumerable: true,
  86474. configurable: true
  86475. });
  86476. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  86477. /**
  86478. * Gets the perf counter used for particles render time
  86479. */
  86480. get: function () {
  86481. return this._particlesRenderTime;
  86482. },
  86483. enumerable: true,
  86484. configurable: true
  86485. });
  86486. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  86487. /**
  86488. * Gets the particles render time capture status
  86489. */
  86490. get: function () {
  86491. return this._captureParticlesRenderTime;
  86492. },
  86493. /**
  86494. * Enable or disable the particles render time capture
  86495. */
  86496. set: function (value) {
  86497. var _this = this;
  86498. if (value === this._captureParticlesRenderTime) {
  86499. return;
  86500. }
  86501. this._captureParticlesRenderTime = value;
  86502. if (value) {
  86503. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  86504. BABYLON.Tools.StartPerformanceCounter("Particles");
  86505. _this._particlesRenderTime.beginMonitoring();
  86506. });
  86507. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  86508. BABYLON.Tools.EndPerformanceCounter("Particles");
  86509. _this._particlesRenderTime.endMonitoring(false);
  86510. });
  86511. }
  86512. else {
  86513. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86514. this._onBeforeParticlesRenderingObserver = null;
  86515. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86516. this._onAfterParticlesRenderingObserver = null;
  86517. }
  86518. },
  86519. enumerable: true,
  86520. configurable: true
  86521. });
  86522. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  86523. /**
  86524. * Gets the perf counter used for sprites render time
  86525. */
  86526. get: function () {
  86527. return this._spritesRenderTime;
  86528. },
  86529. enumerable: true,
  86530. configurable: true
  86531. });
  86532. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  86533. /**
  86534. * Gets the sprites render time capture status
  86535. */
  86536. get: function () {
  86537. return this._captureSpritesRenderTime;
  86538. },
  86539. /**
  86540. * Enable or disable the sprites render time capture
  86541. */
  86542. set: function (value) {
  86543. var _this = this;
  86544. if (value === this._captureSpritesRenderTime) {
  86545. return;
  86546. }
  86547. this._captureSpritesRenderTime = value;
  86548. if (value) {
  86549. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  86550. BABYLON.Tools.StartPerformanceCounter("Sprites");
  86551. _this._spritesRenderTime.beginMonitoring();
  86552. });
  86553. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  86554. BABYLON.Tools.EndPerformanceCounter("Sprites");
  86555. _this._spritesRenderTime.endMonitoring(false);
  86556. });
  86557. }
  86558. else {
  86559. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86560. this._onBeforeSpritesRenderingObserver = null;
  86561. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86562. this._onAfterSpritesRenderingObserver = null;
  86563. }
  86564. },
  86565. enumerable: true,
  86566. configurable: true
  86567. });
  86568. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  86569. /**
  86570. * Gets the perf counter used for physics time
  86571. */
  86572. get: function () {
  86573. return this._physicsTime;
  86574. },
  86575. enumerable: true,
  86576. configurable: true
  86577. });
  86578. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  86579. /**
  86580. * Gets the physics time capture status
  86581. */
  86582. get: function () {
  86583. return this._capturePhysicsTime;
  86584. },
  86585. /**
  86586. * Enable or disable the physics time capture
  86587. */
  86588. set: function (value) {
  86589. var _this = this;
  86590. if (value === this._capturePhysicsTime) {
  86591. return;
  86592. }
  86593. this._capturePhysicsTime = value;
  86594. if (value) {
  86595. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  86596. BABYLON.Tools.StartPerformanceCounter("Physics");
  86597. _this._physicsTime.beginMonitoring();
  86598. });
  86599. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  86600. BABYLON.Tools.EndPerformanceCounter("Physics");
  86601. _this._physicsTime.endMonitoring();
  86602. });
  86603. }
  86604. else {
  86605. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86606. this._onBeforePhysicsObserver = null;
  86607. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86608. this._onAfterPhysicsObserver = null;
  86609. }
  86610. },
  86611. enumerable: true,
  86612. configurable: true
  86613. });
  86614. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  86615. /**
  86616. * Gets the perf counter used for animations time
  86617. */
  86618. get: function () {
  86619. return this._animationsTime;
  86620. },
  86621. enumerable: true,
  86622. configurable: true
  86623. });
  86624. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  86625. /**
  86626. * Gets the animations time capture status
  86627. */
  86628. get: function () {
  86629. return this._captureAnimationsTime;
  86630. },
  86631. /**
  86632. * Enable or disable the animations time capture
  86633. */
  86634. set: function (value) {
  86635. var _this = this;
  86636. if (value === this._captureAnimationsTime) {
  86637. return;
  86638. }
  86639. this._captureAnimationsTime = value;
  86640. if (value) {
  86641. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  86642. _this._animationsTime.endMonitoring();
  86643. });
  86644. }
  86645. else {
  86646. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86647. this._onAfterAnimationsObserver = null;
  86648. }
  86649. },
  86650. enumerable: true,
  86651. configurable: true
  86652. });
  86653. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  86654. /**
  86655. * Gets the perf counter used for frame time capture
  86656. */
  86657. get: function () {
  86658. return this._frameTime;
  86659. },
  86660. enumerable: true,
  86661. configurable: true
  86662. });
  86663. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  86664. /**
  86665. * Gets the frame time capture status
  86666. */
  86667. get: function () {
  86668. return this._captureFrameTime;
  86669. },
  86670. /**
  86671. * Enable or disable the frame time capture
  86672. */
  86673. set: function (value) {
  86674. this._captureFrameTime = value;
  86675. },
  86676. enumerable: true,
  86677. configurable: true
  86678. });
  86679. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  86680. /**
  86681. * Gets the perf counter used for inter-frames time capture
  86682. */
  86683. get: function () {
  86684. return this._interFrameTime;
  86685. },
  86686. enumerable: true,
  86687. configurable: true
  86688. });
  86689. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  86690. /**
  86691. * Gets the inter-frames time capture status
  86692. */
  86693. get: function () {
  86694. return this._captureInterFrameTime;
  86695. },
  86696. /**
  86697. * Enable or disable the inter-frames time capture
  86698. */
  86699. set: function (value) {
  86700. this._captureInterFrameTime = value;
  86701. },
  86702. enumerable: true,
  86703. configurable: true
  86704. });
  86705. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  86706. /**
  86707. * Gets the perf counter used for render time capture
  86708. */
  86709. get: function () {
  86710. return this._renderTime;
  86711. },
  86712. enumerable: true,
  86713. configurable: true
  86714. });
  86715. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  86716. /**
  86717. * Gets the render time capture status
  86718. */
  86719. get: function () {
  86720. return this._captureRenderTime;
  86721. },
  86722. /**
  86723. * Enable or disable the render time capture
  86724. */
  86725. set: function (value) {
  86726. var _this = this;
  86727. if (value === this._captureRenderTime) {
  86728. return;
  86729. }
  86730. this._captureRenderTime = value;
  86731. if (value) {
  86732. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  86733. _this._renderTime.beginMonitoring();
  86734. BABYLON.Tools.StartPerformanceCounter("Main render");
  86735. });
  86736. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  86737. _this._renderTime.endMonitoring(false);
  86738. BABYLON.Tools.EndPerformanceCounter("Main render");
  86739. });
  86740. }
  86741. else {
  86742. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86743. this._onBeforeDrawPhaseObserver = null;
  86744. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86745. this._onAfterDrawPhaseObserver = null;
  86746. }
  86747. },
  86748. enumerable: true,
  86749. configurable: true
  86750. });
  86751. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  86752. /**
  86753. * Gets the perf counter used for draw calls
  86754. */
  86755. get: function () {
  86756. return this.scene.getEngine()._drawCalls;
  86757. },
  86758. enumerable: true,
  86759. configurable: true
  86760. });
  86761. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  86762. /**
  86763. * Gets the perf counter used for texture collisions
  86764. */
  86765. get: function () {
  86766. return this.scene.getEngine()._textureCollisions;
  86767. },
  86768. enumerable: true,
  86769. configurable: true
  86770. });
  86771. SceneInstrumentation.prototype.dispose = function () {
  86772. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86773. this._onAfterRenderObserver = null;
  86774. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86775. this._onBeforeActiveMeshesEvaluationObserver = null;
  86776. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86777. this._onAfterActiveMeshesEvaluationObserver = null;
  86778. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86779. this._onBeforeRenderTargetsRenderObserver = null;
  86780. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86781. this._onAfterRenderTargetsRenderObserver = null;
  86782. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  86783. this._onBeforeAnimationsObserver = null;
  86784. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86785. this._onBeforeParticlesRenderingObserver = null;
  86786. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86787. this._onAfterParticlesRenderingObserver = null;
  86788. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86789. this._onBeforeSpritesRenderingObserver = null;
  86790. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86791. this._onAfterSpritesRenderingObserver = null;
  86792. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86793. this._onBeforeDrawPhaseObserver = null;
  86794. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86795. this._onAfterDrawPhaseObserver = null;
  86796. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86797. this._onBeforePhysicsObserver = null;
  86798. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86799. this._onAfterPhysicsObserver = null;
  86800. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86801. this._onAfterAnimationsObserver = null;
  86802. this.scene = null;
  86803. };
  86804. return SceneInstrumentation;
  86805. }());
  86806. BABYLON.SceneInstrumentation = SceneInstrumentation;
  86807. })(BABYLON || (BABYLON = {}));
  86808. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  86809. var BABYLON;
  86810. (function (BABYLON) {
  86811. var _TimeToken = /** @class */ (function () {
  86812. function _TimeToken() {
  86813. this._timeElapsedQueryEnded = false;
  86814. }
  86815. return _TimeToken;
  86816. }());
  86817. BABYLON._TimeToken = _TimeToken;
  86818. })(BABYLON || (BABYLON = {}));
  86819. //# sourceMappingURL=babylon.timeToken.js.map
  86820. var BABYLON;
  86821. (function (BABYLON) {
  86822. /**
  86823. * Background material defines definition.
  86824. * @ignore Mainly internal Use
  86825. */
  86826. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  86827. __extends(BackgroundMaterialDefines, _super);
  86828. /**
  86829. * Constructor of the defines.
  86830. */
  86831. function BackgroundMaterialDefines() {
  86832. var _this = _super.call(this) || this;
  86833. /**
  86834. * True if the diffuse texture is in use.
  86835. */
  86836. _this.DIFFUSE = false;
  86837. /**
  86838. * The direct UV channel to use.
  86839. */
  86840. _this.DIFFUSEDIRECTUV = 0;
  86841. /**
  86842. * True if the diffuse texture is in gamma space.
  86843. */
  86844. _this.GAMMADIFFUSE = false;
  86845. /**
  86846. * True if the diffuse texture has opacity in the alpha channel.
  86847. */
  86848. _this.DIFFUSEHASALPHA = false;
  86849. /**
  86850. * True if you want the material to fade to transparent at grazing angle.
  86851. */
  86852. _this.OPACITYFRESNEL = false;
  86853. /**
  86854. * True if an extra blur needs to be added in the reflection.
  86855. */
  86856. _this.REFLECTIONBLUR = false;
  86857. /**
  86858. * True if you want the material to fade to reflection at grazing angle.
  86859. */
  86860. _this.REFLECTIONFRESNEL = false;
  86861. /**
  86862. * True if you want the material to falloff as far as you move away from the scene center.
  86863. */
  86864. _this.REFLECTIONFALLOFF = false;
  86865. /**
  86866. * False if the current Webgl implementation does not support the texture lod extension.
  86867. */
  86868. _this.TEXTURELODSUPPORT = false;
  86869. /**
  86870. * True to ensure the data are premultiplied.
  86871. */
  86872. _this.PREMULTIPLYALPHA = false;
  86873. /**
  86874. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  86875. */
  86876. _this.USERGBCOLOR = false;
  86877. /**
  86878. * True to add noise in order to reduce the banding effect.
  86879. */
  86880. _this.NOISE = false;
  86881. // Image Processing Configuration.
  86882. _this.IMAGEPROCESSING = false;
  86883. _this.VIGNETTE = false;
  86884. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  86885. _this.VIGNETTEBLENDMODEOPAQUE = false;
  86886. _this.TONEMAPPING = false;
  86887. _this.CONTRAST = false;
  86888. _this.COLORCURVES = false;
  86889. _this.COLORGRADING = false;
  86890. _this.COLORGRADING3D = false;
  86891. _this.SAMPLER3DGREENDEPTH = false;
  86892. _this.SAMPLER3DBGRMAP = false;
  86893. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  86894. _this.EXPOSURE = false;
  86895. // Reflection.
  86896. _this.REFLECTION = false;
  86897. _this.REFLECTIONMAP_3D = false;
  86898. _this.REFLECTIONMAP_SPHERICAL = false;
  86899. _this.REFLECTIONMAP_PLANAR = false;
  86900. _this.REFLECTIONMAP_CUBIC = false;
  86901. _this.REFLECTIONMAP_PROJECTION = false;
  86902. _this.REFLECTIONMAP_SKYBOX = false;
  86903. _this.REFLECTIONMAP_EXPLICIT = false;
  86904. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86905. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86906. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86907. _this.INVERTCUBICMAP = false;
  86908. _this.REFLECTIONMAP_OPPOSITEZ = false;
  86909. _this.LODINREFLECTIONALPHA = false;
  86910. _this.GAMMAREFLECTION = false;
  86911. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  86912. // Default BJS.
  86913. _this.MAINUV1 = false;
  86914. _this.MAINUV2 = false;
  86915. _this.UV1 = false;
  86916. _this.UV2 = false;
  86917. _this.CLIPPLANE = false;
  86918. _this.POINTSIZE = false;
  86919. _this.FOG = false;
  86920. _this.NORMAL = false;
  86921. _this.NUM_BONE_INFLUENCERS = 0;
  86922. _this.BonesPerMesh = 0;
  86923. _this.INSTANCES = false;
  86924. _this.SHADOWFLOAT = false;
  86925. _this.rebuild();
  86926. return _this;
  86927. }
  86928. return BackgroundMaterialDefines;
  86929. }(BABYLON.MaterialDefines));
  86930. /**
  86931. * Background material used to create an efficient environement around your scene.
  86932. */
  86933. var BackgroundMaterial = /** @class */ (function (_super) {
  86934. __extends(BackgroundMaterial, _super);
  86935. /**
  86936. * Instantiates a Background Material in the given scene
  86937. * @param name The friendly name of the material
  86938. * @param scene The scene to add the material to
  86939. */
  86940. function BackgroundMaterial(name, scene) {
  86941. var _this = _super.call(this, name, scene) || this;
  86942. /**
  86943. * Key light Color (multiply against the R channel of the environement texture)
  86944. */
  86945. _this.primaryColor = BABYLON.Color3.White();
  86946. /**
  86947. * Key light Level (allowing HDR output of the background)
  86948. */
  86949. _this.primaryLevel = 1;
  86950. /**
  86951. * Secondary light Color (multiply against the G channel of the environement texture)
  86952. */
  86953. _this.secondaryColor = BABYLON.Color3.Gray();
  86954. /**
  86955. * Secondary light Level (allowing HDR output of the background)
  86956. */
  86957. _this.secondaryLevel = 1;
  86958. /**
  86959. * Tertiary light Color (multiply against the B channel of the environement texture)
  86960. */
  86961. _this.tertiaryColor = BABYLON.Color3.Black();
  86962. /**
  86963. * Tertiary light Level (allowing HDR output of the background)
  86964. */
  86965. _this.tertiaryLevel = 1;
  86966. /**
  86967. * Reflection Texture used in the material.
  86968. * Should be author in a specific way for the best result (refer to the documentation).
  86969. */
  86970. _this.reflectionTexture = null;
  86971. /**
  86972. * Reflection Texture level of blur.
  86973. *
  86974. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  86975. * texture twice.
  86976. */
  86977. _this.reflectionBlur = 0;
  86978. /**
  86979. * Diffuse Texture used in the material.
  86980. * Should be author in a specific way for the best result (refer to the documentation).
  86981. */
  86982. _this.diffuseTexture = null;
  86983. _this._shadowLights = null;
  86984. /**
  86985. * Specify the list of lights casting shadow on the material.
  86986. * All scene shadow lights will be included if null.
  86987. */
  86988. _this.shadowLights = null;
  86989. /**
  86990. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  86991. * soft lighting on the background.
  86992. */
  86993. _this.shadowBlurScale = 1;
  86994. /**
  86995. * Helps adjusting the shadow to a softer level if required.
  86996. * 0 means black shadows and 1 means no shadows.
  86997. */
  86998. _this.shadowLevel = 0;
  86999. /**
  87000. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  87001. * It is usually zero but might be interesting to modify according to your setup.
  87002. */
  87003. _this.sceneCenter = BABYLON.Vector3.Zero();
  87004. /**
  87005. * This helps specifying that the material is falling off to the sky box at grazing angle.
  87006. * This helps ensuring a nice transition when the camera goes under the ground.
  87007. */
  87008. _this.opacityFresnel = true;
  87009. /**
  87010. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  87011. * This helps adding a mirror texture on the ground.
  87012. */
  87013. _this.reflectionFresnel = false;
  87014. /**
  87015. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  87016. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  87017. */
  87018. _this.reflectionFalloffDistance = 0.0;
  87019. /**
  87020. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  87021. */
  87022. _this.reflectionAmount = 1.0;
  87023. /**
  87024. * This specifies the weight of the reflection at grazing angle.
  87025. */
  87026. _this.reflectionReflectance0 = 0.05;
  87027. /**
  87028. * This specifies the weight of the reflection at a perpendicular point of view.
  87029. */
  87030. _this.reflectionReflectance90 = 0.5;
  87031. /**
  87032. * Helps to directly use the maps channels instead of their level.
  87033. */
  87034. _this.useRGBColor = true;
  87035. /**
  87036. * This helps reducing the banding effect that could occur on the background.
  87037. */
  87038. _this.enableNoise = false;
  87039. _this._fovMultiplier = 1.0;
  87040. /**
  87041. * Enable the FOV adjustment feature controlled by fovMultiplier.
  87042. * @type {boolean}
  87043. */
  87044. _this.useEquirectangularFOV = false;
  87045. _this._maxSimultaneousLights = 4;
  87046. /**
  87047. * Number of Simultaneous lights allowed on the material.
  87048. */
  87049. _this.maxSimultaneousLights = 4;
  87050. /**
  87051. * Keep track of the image processing observer to allow dispose and replace.
  87052. */
  87053. _this._imageProcessingObserver = null;
  87054. // Temp values kept as cache in the material.
  87055. _this._renderTargets = new BABYLON.SmartArray(16);
  87056. _this._reflectionControls = BABYLON.Vector4.Zero();
  87057. // Setup the default processing configuration to the scene.
  87058. _this._attachImageProcessingConfiguration(null);
  87059. _this.getRenderTargetTextures = function () {
  87060. _this._renderTargets.reset();
  87061. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  87062. _this._renderTargets.push(_this._diffuseTexture);
  87063. }
  87064. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  87065. _this._renderTargets.push(_this._reflectionTexture);
  87066. }
  87067. return _this._renderTargets;
  87068. };
  87069. return _this;
  87070. }
  87071. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  87072. /**
  87073. * Sets the reflection reflectance fresnel values according to the default standard
  87074. * empirically know to work well :-)
  87075. */
  87076. set: function (value) {
  87077. var reflectionWeight = value;
  87078. if (reflectionWeight < 0.5) {
  87079. reflectionWeight = reflectionWeight * 2.0;
  87080. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  87081. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  87082. }
  87083. else {
  87084. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  87085. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  87086. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  87087. }
  87088. },
  87089. enumerable: true,
  87090. configurable: true
  87091. });
  87092. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  87093. /**
  87094. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  87095. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  87096. * Recommended to be keep at 1.0 except for special cases.
  87097. */
  87098. get: function () {
  87099. return this._fovMultiplier;
  87100. },
  87101. set: function (value) {
  87102. if (isNaN(value)) {
  87103. value = 1.0;
  87104. }
  87105. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  87106. },
  87107. enumerable: true,
  87108. configurable: true
  87109. });
  87110. /**
  87111. * Attaches a new image processing configuration to the PBR Material.
  87112. * @param configuration (if null the scene configuration will be use)
  87113. */
  87114. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  87115. var _this = this;
  87116. if (configuration === this._imageProcessingConfiguration) {
  87117. return;
  87118. }
  87119. // Detaches observer.
  87120. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87121. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87122. }
  87123. // Pick the scene configuration if needed.
  87124. if (!configuration) {
  87125. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  87126. }
  87127. else {
  87128. this._imageProcessingConfiguration = configuration;
  87129. }
  87130. // Attaches observer.
  87131. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  87132. _this._markAllSubMeshesAsImageProcessingDirty();
  87133. });
  87134. };
  87135. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  87136. /**
  87137. * Gets the image processing configuration used either in this material.
  87138. */
  87139. get: function () {
  87140. return this._imageProcessingConfiguration;
  87141. },
  87142. /**
  87143. * Sets the Default image processing configuration used either in the this material.
  87144. *
  87145. * If sets to null, the scene one is in use.
  87146. */
  87147. set: function (value) {
  87148. this._attachImageProcessingConfiguration(value);
  87149. // Ensure the effect will be rebuilt.
  87150. this._markAllSubMeshesAsTexturesDirty();
  87151. },
  87152. enumerable: true,
  87153. configurable: true
  87154. });
  87155. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  87156. /**
  87157. * Gets wether the color curves effect is enabled.
  87158. */
  87159. get: function () {
  87160. return this.imageProcessingConfiguration.colorCurvesEnabled;
  87161. },
  87162. /**
  87163. * Sets wether the color curves effect is enabled.
  87164. */
  87165. set: function (value) {
  87166. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  87167. },
  87168. enumerable: true,
  87169. configurable: true
  87170. });
  87171. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  87172. /**
  87173. * Gets wether the color grading effect is enabled.
  87174. */
  87175. get: function () {
  87176. return this.imageProcessingConfiguration.colorGradingEnabled;
  87177. },
  87178. /**
  87179. * Gets wether the color grading effect is enabled.
  87180. */
  87181. set: function (value) {
  87182. this.imageProcessingConfiguration.colorGradingEnabled = value;
  87183. },
  87184. enumerable: true,
  87185. configurable: true
  87186. });
  87187. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  87188. /**
  87189. * Gets wether tonemapping is enabled or not.
  87190. */
  87191. get: function () {
  87192. return this._imageProcessingConfiguration.toneMappingEnabled;
  87193. },
  87194. /**
  87195. * Sets wether tonemapping is enabled or not
  87196. */
  87197. set: function (value) {
  87198. this._imageProcessingConfiguration.toneMappingEnabled = value;
  87199. },
  87200. enumerable: true,
  87201. configurable: true
  87202. });
  87203. ;
  87204. ;
  87205. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  87206. /**
  87207. * The camera exposure used on this material.
  87208. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  87209. * This corresponds to a photographic exposure.
  87210. */
  87211. get: function () {
  87212. return this._imageProcessingConfiguration.exposure;
  87213. },
  87214. /**
  87215. * The camera exposure used on this material.
  87216. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  87217. * This corresponds to a photographic exposure.
  87218. */
  87219. set: function (value) {
  87220. this._imageProcessingConfiguration.exposure = value;
  87221. },
  87222. enumerable: true,
  87223. configurable: true
  87224. });
  87225. ;
  87226. ;
  87227. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  87228. /**
  87229. * Gets The camera contrast used on this material.
  87230. */
  87231. get: function () {
  87232. return this._imageProcessingConfiguration.contrast;
  87233. },
  87234. /**
  87235. * Sets The camera contrast used on this material.
  87236. */
  87237. set: function (value) {
  87238. this._imageProcessingConfiguration.contrast = value;
  87239. },
  87240. enumerable: true,
  87241. configurable: true
  87242. });
  87243. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  87244. /**
  87245. * Gets the Color Grading 2D Lookup Texture.
  87246. */
  87247. get: function () {
  87248. return this._imageProcessingConfiguration.colorGradingTexture;
  87249. },
  87250. /**
  87251. * Sets the Color Grading 2D Lookup Texture.
  87252. */
  87253. set: function (value) {
  87254. this.imageProcessingConfiguration.colorGradingTexture = value;
  87255. },
  87256. enumerable: true,
  87257. configurable: true
  87258. });
  87259. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  87260. /**
  87261. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87262. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87263. * 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;
  87264. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87265. */
  87266. get: function () {
  87267. return this.imageProcessingConfiguration.colorCurves;
  87268. },
  87269. /**
  87270. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87271. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87272. * 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;
  87273. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87274. */
  87275. set: function (value) {
  87276. this.imageProcessingConfiguration.colorCurves = value;
  87277. },
  87278. enumerable: true,
  87279. configurable: true
  87280. });
  87281. /**
  87282. * The entire material has been created in order to prevent overdraw.
  87283. * @returns false
  87284. */
  87285. BackgroundMaterial.prototype.needAlphaTesting = function () {
  87286. return true;
  87287. };
  87288. /**
  87289. * The entire material has been created in order to prevent overdraw.
  87290. * @returns true if blending is enable
  87291. */
  87292. BackgroundMaterial.prototype.needAlphaBlending = function () {
  87293. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  87294. };
  87295. /**
  87296. * Checks wether the material is ready to be rendered for a given mesh.
  87297. * @param mesh The mesh to render
  87298. * @param subMesh The submesh to check against
  87299. * @param useInstances Specify wether or not the material is used with instances
  87300. * @returns true if all the dependencies are ready (Textures, Effects...)
  87301. */
  87302. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  87303. var _this = this;
  87304. if (useInstances === void 0) { useInstances = false; }
  87305. if (subMesh.effect && this.isFrozen) {
  87306. if (this._wasPreviouslyReady) {
  87307. return true;
  87308. }
  87309. }
  87310. if (!subMesh._materialDefines) {
  87311. subMesh._materialDefines = new BackgroundMaterialDefines();
  87312. }
  87313. var scene = this.getScene();
  87314. var defines = subMesh._materialDefines;
  87315. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  87316. if (defines._renderId === scene.getRenderId()) {
  87317. return true;
  87318. }
  87319. }
  87320. var engine = scene.getEngine();
  87321. // Lights
  87322. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  87323. defines._needNormals = true;
  87324. // Textures
  87325. if (defines._areTexturesDirty) {
  87326. defines._needUVs = false;
  87327. if (scene.texturesEnabled) {
  87328. if (scene.getEngine().getCaps().textureLOD) {
  87329. defines.TEXTURELODSUPPORT = true;
  87330. }
  87331. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87332. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  87333. return false;
  87334. }
  87335. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  87336. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  87337. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  87338. defines.OPACITYFRESNEL = this._opacityFresnel;
  87339. }
  87340. else {
  87341. defines.DIFFUSE = false;
  87342. defines.DIFFUSEHASALPHA = false;
  87343. defines.GAMMADIFFUSE = false;
  87344. defines.OPACITYFRESNEL = false;
  87345. }
  87346. var reflectionTexture = this._reflectionTexture;
  87347. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87348. if (!reflectionTexture.isReadyOrNotBlocking()) {
  87349. return false;
  87350. }
  87351. defines.REFLECTION = true;
  87352. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  87353. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  87354. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  87355. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  87356. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  87357. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  87358. defines.INVERTCUBICMAP = true;
  87359. }
  87360. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  87361. switch (reflectionTexture.coordinatesMode) {
  87362. case BABYLON.Texture.CUBIC_MODE:
  87363. case BABYLON.Texture.INVCUBIC_MODE:
  87364. defines.REFLECTIONMAP_CUBIC = true;
  87365. break;
  87366. case BABYLON.Texture.EXPLICIT_MODE:
  87367. defines.REFLECTIONMAP_EXPLICIT = true;
  87368. break;
  87369. case BABYLON.Texture.PLANAR_MODE:
  87370. defines.REFLECTIONMAP_PLANAR = true;
  87371. break;
  87372. case BABYLON.Texture.PROJECTION_MODE:
  87373. defines.REFLECTIONMAP_PROJECTION = true;
  87374. break;
  87375. case BABYLON.Texture.SKYBOX_MODE:
  87376. defines.REFLECTIONMAP_SKYBOX = true;
  87377. break;
  87378. case BABYLON.Texture.SPHERICAL_MODE:
  87379. defines.REFLECTIONMAP_SPHERICAL = true;
  87380. break;
  87381. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  87382. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  87383. break;
  87384. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  87385. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  87386. break;
  87387. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  87388. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  87389. break;
  87390. }
  87391. if (this.reflectionFresnel) {
  87392. defines.REFLECTIONFRESNEL = true;
  87393. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  87394. this._reflectionControls.x = this.reflectionAmount;
  87395. this._reflectionControls.y = this.reflectionReflectance0;
  87396. this._reflectionControls.z = this.reflectionReflectance90;
  87397. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  87398. }
  87399. else {
  87400. defines.REFLECTIONFRESNEL = false;
  87401. defines.REFLECTIONFALLOFF = false;
  87402. }
  87403. }
  87404. else {
  87405. defines.REFLECTION = false;
  87406. defines.REFLECTIONFALLOFF = false;
  87407. defines.REFLECTIONBLUR = false;
  87408. defines.REFLECTIONMAP_3D = false;
  87409. defines.REFLECTIONMAP_SPHERICAL = false;
  87410. defines.REFLECTIONMAP_PLANAR = false;
  87411. defines.REFLECTIONMAP_CUBIC = false;
  87412. defines.REFLECTIONMAP_PROJECTION = false;
  87413. defines.REFLECTIONMAP_SKYBOX = false;
  87414. defines.REFLECTIONMAP_EXPLICIT = false;
  87415. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  87416. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  87417. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  87418. defines.INVERTCUBICMAP = false;
  87419. defines.REFLECTIONMAP_OPPOSITEZ = false;
  87420. defines.LODINREFLECTIONALPHA = false;
  87421. defines.GAMMAREFLECTION = false;
  87422. }
  87423. }
  87424. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  87425. defines.USERGBCOLOR = this._useRGBColor;
  87426. defines.NOISE = this._enableNoise;
  87427. }
  87428. if (defines._areImageProcessingDirty) {
  87429. if (!this._imageProcessingConfiguration.isReady()) {
  87430. return false;
  87431. }
  87432. this._imageProcessingConfiguration.prepareDefines(defines);
  87433. }
  87434. // Misc.
  87435. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  87436. // Values that need to be evaluated on every frame
  87437. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  87438. // Attribs
  87439. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  87440. if (mesh) {
  87441. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  87442. mesh.createNormals(true);
  87443. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  87444. }
  87445. }
  87446. }
  87447. // Get correct effect
  87448. if (defines.isDirty) {
  87449. defines.markAsProcessed();
  87450. scene.resetCachedMaterial();
  87451. // Fallbacks
  87452. var fallbacks = new BABYLON.EffectFallbacks();
  87453. if (defines.FOG) {
  87454. fallbacks.addFallback(0, "FOG");
  87455. }
  87456. if (defines.POINTSIZE) {
  87457. fallbacks.addFallback(1, "POINTSIZE");
  87458. }
  87459. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  87460. if (defines.NUM_BONE_INFLUENCERS > 0) {
  87461. fallbacks.addCPUSkinningFallback(0, mesh);
  87462. }
  87463. //Attributes
  87464. var attribs = [BABYLON.VertexBuffer.PositionKind];
  87465. if (defines.NORMAL) {
  87466. attribs.push(BABYLON.VertexBuffer.NormalKind);
  87467. }
  87468. if (defines.UV1) {
  87469. attribs.push(BABYLON.VertexBuffer.UVKind);
  87470. }
  87471. if (defines.UV2) {
  87472. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  87473. }
  87474. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  87475. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  87476. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  87477. "vFogInfos", "vFogColor", "pointSize",
  87478. "vClipPlane", "mBones",
  87479. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  87480. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  87481. "shadowLevel", "alpha",
  87482. "vBackgroundCenter", "vReflectionControl",
  87483. "vDiffuseInfos", "diffuseMatrix",
  87484. ];
  87485. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  87486. var uniformBuffers = ["Material", "Scene"];
  87487. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  87488. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  87489. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  87490. uniformsNames: uniforms,
  87491. uniformBuffersNames: uniformBuffers,
  87492. samplers: samplers,
  87493. defines: defines,
  87494. maxSimultaneousLights: this._maxSimultaneousLights
  87495. });
  87496. var onCompiled = function (effect) {
  87497. if (_this.onCompiled) {
  87498. _this.onCompiled(effect);
  87499. }
  87500. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  87501. };
  87502. var join = defines.toString();
  87503. subMesh.setEffect(scene.getEngine().createEffect("background", {
  87504. attributes: attribs,
  87505. uniformsNames: uniforms,
  87506. uniformBuffersNames: uniformBuffers,
  87507. samplers: samplers,
  87508. defines: join,
  87509. fallbacks: fallbacks,
  87510. onCompiled: onCompiled,
  87511. onError: this.onError,
  87512. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  87513. }, engine), defines);
  87514. this.buildUniformLayout();
  87515. }
  87516. if (!subMesh.effect || !subMesh.effect.isReady()) {
  87517. return false;
  87518. }
  87519. defines._renderId = scene.getRenderId();
  87520. this._wasPreviouslyReady = true;
  87521. return true;
  87522. };
  87523. /**
  87524. * Build the uniform buffer used in the material.
  87525. */
  87526. BackgroundMaterial.prototype.buildUniformLayout = function () {
  87527. // Order is important !
  87528. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  87529. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  87530. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  87531. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  87532. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  87533. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  87534. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  87535. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  87536. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  87537. this._uniformBuffer.addUniform("pointSize", 1);
  87538. this._uniformBuffer.addUniform("shadowLevel", 1);
  87539. this._uniformBuffer.addUniform("alpha", 1);
  87540. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  87541. this._uniformBuffer.addUniform("vReflectionControl", 4);
  87542. this._uniformBuffer.create();
  87543. };
  87544. /**
  87545. * Unbind the material.
  87546. */
  87547. BackgroundMaterial.prototype.unbind = function () {
  87548. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  87549. this._uniformBuffer.setTexture("diffuseSampler", null);
  87550. }
  87551. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  87552. this._uniformBuffer.setTexture("reflectionSampler", null);
  87553. }
  87554. _super.prototype.unbind.call(this);
  87555. };
  87556. /**
  87557. * Bind only the world matrix to the material.
  87558. * @param world The world matrix to bind.
  87559. */
  87560. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  87561. this._activeEffect.setMatrix("world", world);
  87562. };
  87563. /**
  87564. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  87565. * @param world The world matrix to bind.
  87566. * @param subMesh The submesh to bind for.
  87567. */
  87568. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  87569. var scene = this.getScene();
  87570. var defines = subMesh._materialDefines;
  87571. if (!defines) {
  87572. return;
  87573. }
  87574. var effect = subMesh.effect;
  87575. if (!effect) {
  87576. return;
  87577. }
  87578. this._activeEffect = effect;
  87579. // Matrices
  87580. this.bindOnlyWorldMatrix(world);
  87581. // Bones
  87582. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  87583. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  87584. if (mustRebind) {
  87585. this._uniformBuffer.bindToEffect(effect, "Material");
  87586. this.bindViewProjection(effect);
  87587. var reflectionTexture = this._reflectionTexture;
  87588. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  87589. // Texture uniforms
  87590. if (scene.texturesEnabled) {
  87591. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87592. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  87593. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  87594. }
  87595. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87596. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  87597. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  87598. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  87599. }
  87600. }
  87601. if (this.shadowLevel > 0) {
  87602. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  87603. }
  87604. this._uniformBuffer.updateFloat("alpha", this.alpha);
  87605. // Point size
  87606. if (this.pointsCloud) {
  87607. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  87608. }
  87609. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  87610. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  87611. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  87612. }
  87613. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  87614. // Textures
  87615. if (scene.texturesEnabled) {
  87616. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87617. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  87618. }
  87619. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87620. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  87621. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87622. }
  87623. else if (!defines.REFLECTIONBLUR) {
  87624. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87625. }
  87626. else {
  87627. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  87628. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  87629. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  87630. }
  87631. if (defines.REFLECTIONFRESNEL) {
  87632. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  87633. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  87634. }
  87635. }
  87636. }
  87637. // Clip plane
  87638. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  87639. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  87640. }
  87641. if (mustRebind || !this.isFrozen) {
  87642. if (scene.lightsEnabled) {
  87643. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  87644. }
  87645. // View
  87646. this.bindView(effect);
  87647. // Fog
  87648. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  87649. // image processing
  87650. this._imageProcessingConfiguration.bind(this._activeEffect);
  87651. }
  87652. this._uniformBuffer.update();
  87653. this._afterBind(mesh);
  87654. };
  87655. /**
  87656. * Dispose the material.
  87657. * @param forceDisposeEffect Force disposal of the associated effect.
  87658. * @param forceDisposeTextures Force disposal of the associated textures.
  87659. */
  87660. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  87661. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  87662. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  87663. if (forceDisposeTextures) {
  87664. if (this.diffuseTexture) {
  87665. this.diffuseTexture.dispose();
  87666. }
  87667. if (this.reflectionTexture) {
  87668. this.reflectionTexture.dispose();
  87669. }
  87670. }
  87671. this._renderTargets.dispose();
  87672. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87673. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87674. }
  87675. _super.prototype.dispose.call(this, forceDisposeEffect);
  87676. };
  87677. /**
  87678. * Clones the material.
  87679. * @param name The cloned name.
  87680. * @returns The cloned material.
  87681. */
  87682. BackgroundMaterial.prototype.clone = function (name) {
  87683. var _this = this;
  87684. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  87685. };
  87686. /**
  87687. * Serializes the current material to its JSON representation.
  87688. * @returns The JSON representation.
  87689. */
  87690. BackgroundMaterial.prototype.serialize = function () {
  87691. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87692. serializationObject.customType = "BABYLON.BackgroundMaterial";
  87693. return serializationObject;
  87694. };
  87695. /**
  87696. * Gets the class name of the material
  87697. * @returns "BackgroundMaterial"
  87698. */
  87699. BackgroundMaterial.prototype.getClassName = function () {
  87700. return "BackgroundMaterial";
  87701. };
  87702. /**
  87703. * Parse a JSON input to create back a background material.
  87704. * @param source The JSON data to parse
  87705. * @param scene The scene to create the parsed material in
  87706. * @param rootUrl The root url of the assets the material depends upon
  87707. * @returns the instantiated BackgroundMaterial.
  87708. */
  87709. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  87710. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  87711. };
  87712. /**
  87713. * Standard reflectance value at parallel view angle.
  87714. */
  87715. BackgroundMaterial.StandardReflectance0 = 0.05;
  87716. /**
  87717. * Standard reflectance value at grazing angle.
  87718. */
  87719. BackgroundMaterial.StandardReflectance90 = 0.5;
  87720. __decorate([
  87721. BABYLON.serializeAsColor3()
  87722. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  87723. __decorate([
  87724. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87725. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  87726. __decorate([
  87727. BABYLON.serialize()
  87728. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  87729. __decorate([
  87730. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87731. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  87732. __decorate([
  87733. BABYLON.serializeAsColor3()
  87734. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  87735. __decorate([
  87736. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87737. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  87738. __decorate([
  87739. BABYLON.serialize()
  87740. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  87741. __decorate([
  87742. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87743. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  87744. __decorate([
  87745. BABYLON.serializeAsColor3()
  87746. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  87747. __decorate([
  87748. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87749. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  87750. __decorate([
  87751. BABYLON.serialize()
  87752. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  87753. __decorate([
  87754. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87755. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  87756. __decorate([
  87757. BABYLON.serializeAsTexture()
  87758. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  87759. __decorate([
  87760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87761. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  87762. __decorate([
  87763. BABYLON.serialize()
  87764. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  87765. __decorate([
  87766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87767. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  87768. __decorate([
  87769. BABYLON.serializeAsTexture()
  87770. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  87771. __decorate([
  87772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87773. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  87774. __decorate([
  87775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87776. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  87777. __decorate([
  87778. BABYLON.serialize()
  87779. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  87780. __decorate([
  87781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87782. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  87783. __decorate([
  87784. BABYLON.serialize()
  87785. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  87786. __decorate([
  87787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87788. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  87789. __decorate([
  87790. BABYLON.serializeAsVector3()
  87791. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  87792. __decorate([
  87793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87794. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  87795. __decorate([
  87796. BABYLON.serialize()
  87797. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  87798. __decorate([
  87799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87800. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  87801. __decorate([
  87802. BABYLON.serialize()
  87803. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  87804. __decorate([
  87805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87806. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  87807. __decorate([
  87808. BABYLON.serialize()
  87809. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  87810. __decorate([
  87811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87812. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  87813. __decorate([
  87814. BABYLON.serialize()
  87815. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  87816. __decorate([
  87817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87818. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  87819. __decorate([
  87820. BABYLON.serialize()
  87821. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  87822. __decorate([
  87823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87824. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  87825. __decorate([
  87826. BABYLON.serialize()
  87827. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  87828. __decorate([
  87829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87830. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  87831. __decorate([
  87832. BABYLON.serialize()
  87833. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  87834. __decorate([
  87835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87836. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  87837. __decorate([
  87838. BABYLON.serialize()
  87839. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  87840. __decorate([
  87841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87842. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  87843. __decorate([
  87844. BABYLON.serialize()
  87845. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  87846. __decorate([
  87847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87848. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  87849. __decorate([
  87850. BABYLON.serializeAsImageProcessingConfiguration()
  87851. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  87852. return BackgroundMaterial;
  87853. }(BABYLON.PushMaterial));
  87854. BABYLON.BackgroundMaterial = BackgroundMaterial;
  87855. })(BABYLON || (BABYLON = {}));
  87856. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  87857. var __assign = (this && this.__assign) || Object.assign || function(t) {
  87858. for (var s, i = 1, n = arguments.length; i < n; i++) {
  87859. s = arguments[i];
  87860. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  87861. t[p] = s[p];
  87862. }
  87863. return t;
  87864. };
  87865. var BABYLON;
  87866. (function (BABYLON) {
  87867. /**
  87868. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  87869. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  87870. * It also helps with the default setup of your imageProcessing configuration.
  87871. */
  87872. var EnvironmentHelper = /** @class */ (function () {
  87873. /**
  87874. * constructor
  87875. * @param options
  87876. * @param scene The scene to add the material to
  87877. */
  87878. function EnvironmentHelper(options, scene) {
  87879. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  87880. this._scene = scene;
  87881. this._setupBackground();
  87882. this._setupImageProcessing();
  87883. }
  87884. /**
  87885. * Creates the default options for the helper.
  87886. */
  87887. EnvironmentHelper._getDefaultOptions = function () {
  87888. return {
  87889. createGround: true,
  87890. groundSize: 15,
  87891. groundTexture: this._groundTextureCDNUrl,
  87892. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87893. groundOpacity: 0.9,
  87894. enableGroundShadow: true,
  87895. groundShadowLevel: 0.5,
  87896. enableGroundMirror: false,
  87897. groundMirrorSizeRatio: 0.3,
  87898. groundMirrorBlurKernel: 64,
  87899. groundMirrorAmount: 1,
  87900. groundMirrorFresnelWeight: 1,
  87901. groundMirrorFallOffDistance: 0,
  87902. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  87903. groundYBias: 0.00001,
  87904. createSkybox: true,
  87905. skyboxSize: 20,
  87906. skyboxTexture: this._skyboxTextureCDNUrl,
  87907. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87908. backgroundYRotation: 0,
  87909. sizeAuto: true,
  87910. rootPosition: BABYLON.Vector3.Zero(),
  87911. setupImageProcessing: true,
  87912. environmentTexture: this._environmentTextureCDNUrl,
  87913. cameraExposure: 0.8,
  87914. cameraContrast: 1.2,
  87915. toneMappingEnabled: true,
  87916. };
  87917. };
  87918. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  87919. /**
  87920. * Gets the root mesh created by the helper.
  87921. */
  87922. get: function () {
  87923. return this._rootMesh;
  87924. },
  87925. enumerable: true,
  87926. configurable: true
  87927. });
  87928. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  87929. /**
  87930. * Gets the skybox created by the helper.
  87931. */
  87932. get: function () {
  87933. return this._skybox;
  87934. },
  87935. enumerable: true,
  87936. configurable: true
  87937. });
  87938. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  87939. /**
  87940. * Gets the skybox texture created by the helper.
  87941. */
  87942. get: function () {
  87943. return this._skyboxTexture;
  87944. },
  87945. enumerable: true,
  87946. configurable: true
  87947. });
  87948. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  87949. /**
  87950. * Gets the skybox material created by the helper.
  87951. */
  87952. get: function () {
  87953. return this._skyboxMaterial;
  87954. },
  87955. enumerable: true,
  87956. configurable: true
  87957. });
  87958. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  87959. /**
  87960. * Gets the ground mesh created by the helper.
  87961. */
  87962. get: function () {
  87963. return this._ground;
  87964. },
  87965. enumerable: true,
  87966. configurable: true
  87967. });
  87968. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  87969. /**
  87970. * Gets the ground texture created by the helper.
  87971. */
  87972. get: function () {
  87973. return this._groundTexture;
  87974. },
  87975. enumerable: true,
  87976. configurable: true
  87977. });
  87978. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  87979. /**
  87980. * Gets the ground mirror created by the helper.
  87981. */
  87982. get: function () {
  87983. return this._groundMirror;
  87984. },
  87985. enumerable: true,
  87986. configurable: true
  87987. });
  87988. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  87989. /**
  87990. * Gets the ground mirror render list to helps pushing the meshes
  87991. * you wish in the ground reflection.
  87992. */
  87993. get: function () {
  87994. if (this._groundMirror) {
  87995. return this._groundMirror.renderList;
  87996. }
  87997. return null;
  87998. },
  87999. enumerable: true,
  88000. configurable: true
  88001. });
  88002. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  88003. /**
  88004. * Gets the ground material created by the helper.
  88005. */
  88006. get: function () {
  88007. return this._groundMaterial;
  88008. },
  88009. enumerable: true,
  88010. configurable: true
  88011. });
  88012. /**
  88013. * Updates the background according to the new options
  88014. * @param options
  88015. */
  88016. EnvironmentHelper.prototype.updateOptions = function (options) {
  88017. var newOptions = __assign({}, this._options, options);
  88018. if (this._ground && !newOptions.createGround) {
  88019. this._ground.dispose();
  88020. this._ground = null;
  88021. }
  88022. if (this._groundMaterial && !newOptions.createGround) {
  88023. this._groundMaterial.dispose();
  88024. this._groundMaterial = null;
  88025. }
  88026. if (this._groundTexture) {
  88027. if (this._options.groundTexture != newOptions.groundTexture) {
  88028. this._groundTexture.dispose();
  88029. this._groundTexture = null;
  88030. }
  88031. }
  88032. if (this._skybox && !newOptions.createSkybox) {
  88033. this._skybox.dispose();
  88034. this._skybox = null;
  88035. }
  88036. if (this._skyboxMaterial && !newOptions.createSkybox) {
  88037. this._skyboxMaterial.dispose();
  88038. this._skyboxMaterial = null;
  88039. }
  88040. if (this._skyboxTexture) {
  88041. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  88042. this._skyboxTexture.dispose();
  88043. this._skyboxTexture = null;
  88044. }
  88045. }
  88046. if (this._groundMirror && !newOptions.enableGroundMirror) {
  88047. this._groundMirror.dispose();
  88048. this._groundMirror = null;
  88049. }
  88050. if (this._scene.environmentTexture) {
  88051. if (this._options.environmentTexture != newOptions.environmentTexture) {
  88052. this._scene.environmentTexture.dispose();
  88053. }
  88054. }
  88055. this._options = newOptions;
  88056. this._setupBackground();
  88057. this._setupImageProcessing();
  88058. };
  88059. /**
  88060. * Sets the primary color of all the available elements.
  88061. * @param color
  88062. */
  88063. EnvironmentHelper.prototype.setMainColor = function (color) {
  88064. if (this.groundMaterial) {
  88065. this.groundMaterial.primaryColor = color;
  88066. }
  88067. if (this.skyboxMaterial) {
  88068. this.skyboxMaterial.primaryColor = color;
  88069. }
  88070. if (this.groundMirror) {
  88071. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  88072. }
  88073. };
  88074. /**
  88075. * Setup the image processing according to the specified options.
  88076. */
  88077. EnvironmentHelper.prototype._setupImageProcessing = function () {
  88078. if (this._options.setupImageProcessing) {
  88079. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  88080. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  88081. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  88082. this._setupEnvironmentTexture();
  88083. }
  88084. };
  88085. /**
  88086. * Setup the environment texture according to the specified options.
  88087. */
  88088. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  88089. if (this._scene.environmentTexture) {
  88090. return;
  88091. }
  88092. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  88093. this._scene.environmentTexture = this._options.environmentTexture;
  88094. return;
  88095. }
  88096. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  88097. this._scene.environmentTexture = environmentTexture;
  88098. };
  88099. /**
  88100. * Setup the background according to the specified options.
  88101. */
  88102. EnvironmentHelper.prototype._setupBackground = function () {
  88103. if (!this._rootMesh) {
  88104. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  88105. }
  88106. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  88107. var sceneSize = this._getSceneSize();
  88108. if (this._options.createGround) {
  88109. this._setupGround(sceneSize);
  88110. this._setupGroundMaterial();
  88111. this._setupGroundDiffuseTexture();
  88112. if (this._options.enableGroundMirror) {
  88113. this._setupGroundMirrorTexture(sceneSize);
  88114. }
  88115. this._setupMirrorInGroundMaterial();
  88116. }
  88117. if (this._options.createSkybox) {
  88118. this._setupSkybox(sceneSize);
  88119. this._setupSkyboxMaterial();
  88120. this._setupSkyboxReflectionTexture();
  88121. }
  88122. this._rootMesh.position.x = sceneSize.rootPosition.x;
  88123. this._rootMesh.position.z = sceneSize.rootPosition.z;
  88124. this._rootMesh.position.y = sceneSize.rootPosition.y;
  88125. };
  88126. /**
  88127. * Get the scene sizes according to the setup.
  88128. */
  88129. EnvironmentHelper.prototype._getSceneSize = function () {
  88130. var groundSize = this._options.groundSize;
  88131. var skyboxSize = this._options.skyboxSize;
  88132. var rootPosition = this._options.rootPosition;
  88133. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  88134. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  88135. }
  88136. var sceneExtends = this._scene.getWorldExtends();
  88137. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  88138. if (this._options.sizeAuto) {
  88139. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  88140. this._scene.activeCamera.upperRadiusLimit) {
  88141. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  88142. skyboxSize = groundSize;
  88143. }
  88144. var sceneDiagonalLenght = sceneDiagonal.length();
  88145. if (sceneDiagonalLenght > groundSize) {
  88146. groundSize = sceneDiagonalLenght * 2;
  88147. skyboxSize = groundSize;
  88148. }
  88149. // 10 % bigger.
  88150. groundSize *= 1.1;
  88151. skyboxSize *= 1.5;
  88152. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  88153. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  88154. }
  88155. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  88156. };
  88157. /**
  88158. * Setup the ground according to the specified options.
  88159. */
  88160. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  88161. var _this = this;
  88162. if (!this._ground) {
  88163. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  88164. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  88165. this._ground.parent = this._rootMesh;
  88166. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  88167. }
  88168. this._ground.receiveShadows = this._options.enableGroundShadow;
  88169. };
  88170. /**
  88171. * Setup the ground material according to the specified options.
  88172. */
  88173. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  88174. if (!this._groundMaterial) {
  88175. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  88176. }
  88177. this._groundMaterial.alpha = this._options.groundOpacity;
  88178. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  88179. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  88180. this._groundMaterial.primaryLevel = 1;
  88181. this._groundMaterial.primaryColor = this._options.groundColor;
  88182. this._groundMaterial.secondaryLevel = 0;
  88183. this._groundMaterial.tertiaryLevel = 0;
  88184. this._groundMaterial.useRGBColor = false;
  88185. this._groundMaterial.enableNoise = true;
  88186. if (this._ground) {
  88187. this._ground.material = this._groundMaterial;
  88188. }
  88189. };
  88190. /**
  88191. * Setup the ground diffuse texture according to the specified options.
  88192. */
  88193. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  88194. if (!this._groundMaterial) {
  88195. return;
  88196. }
  88197. if (this._groundTexture) {
  88198. return;
  88199. }
  88200. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  88201. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  88202. return;
  88203. }
  88204. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  88205. diffuseTexture.gammaSpace = false;
  88206. diffuseTexture.hasAlpha = true;
  88207. this._groundMaterial.diffuseTexture = diffuseTexture;
  88208. };
  88209. /**
  88210. * Setup the ground mirror texture according to the specified options.
  88211. */
  88212. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  88213. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88214. if (!this._groundMirror) {
  88215. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  88216. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  88217. this._groundMirror.anisotropicFilteringLevel = 1;
  88218. this._groundMirror.wrapU = wrapping;
  88219. this._groundMirror.wrapV = wrapping;
  88220. this._groundMirror.gammaSpace = false;
  88221. if (this._groundMirror.renderList) {
  88222. for (var i = 0; i < this._scene.meshes.length; i++) {
  88223. var mesh = this._scene.meshes[i];
  88224. if (mesh !== this._ground &&
  88225. mesh !== this._skybox &&
  88226. mesh !== this._rootMesh) {
  88227. this._groundMirror.renderList.push(mesh);
  88228. }
  88229. }
  88230. }
  88231. }
  88232. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  88233. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  88234. };
  88235. /**
  88236. * Setup the ground to receive the mirror texture.
  88237. */
  88238. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  88239. if (this._groundMaterial) {
  88240. this._groundMaterial.reflectionTexture = this._groundMirror;
  88241. this._groundMaterial.reflectionFresnel = true;
  88242. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  88243. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  88244. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  88245. }
  88246. };
  88247. /**
  88248. * Setup the skybox according to the specified options.
  88249. */
  88250. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  88251. var _this = this;
  88252. if (!this._skybox) {
  88253. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  88254. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  88255. }
  88256. this._skybox.parent = this._rootMesh;
  88257. };
  88258. /**
  88259. * Setup the skybox material according to the specified options.
  88260. */
  88261. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  88262. if (!this._skybox) {
  88263. return;
  88264. }
  88265. if (!this._skyboxMaterial) {
  88266. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  88267. }
  88268. this._skyboxMaterial.useRGBColor = false;
  88269. this._skyboxMaterial.primaryLevel = 1;
  88270. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  88271. this._skyboxMaterial.secondaryLevel = 0;
  88272. this._skyboxMaterial.tertiaryLevel = 0;
  88273. this._skyboxMaterial.enableNoise = true;
  88274. this._skybox.material = this._skyboxMaterial;
  88275. };
  88276. /**
  88277. * Setup the skybox reflection texture according to the specified options.
  88278. */
  88279. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  88280. if (!this._skyboxMaterial) {
  88281. return;
  88282. }
  88283. if (this._skyboxTexture) {
  88284. return;
  88285. }
  88286. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  88287. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  88288. return;
  88289. }
  88290. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  88291. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  88292. this._skyboxTexture.gammaSpace = false;
  88293. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  88294. };
  88295. /**
  88296. * Dispose all the elements created by the Helper.
  88297. */
  88298. EnvironmentHelper.prototype.dispose = function () {
  88299. if (this._groundMaterial) {
  88300. this._groundMaterial.dispose(true, true);
  88301. }
  88302. if (this._skyboxMaterial) {
  88303. this._skyboxMaterial.dispose(true, true);
  88304. }
  88305. this._rootMesh.dispose(false);
  88306. };
  88307. /**
  88308. * Default ground texture URL.
  88309. */
  88310. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  88311. /**
  88312. * Default skybox texture URL.
  88313. */
  88314. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  88315. /**
  88316. * Default environment texture URL.
  88317. */
  88318. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  88319. return EnvironmentHelper;
  88320. }());
  88321. BABYLON.EnvironmentHelper = EnvironmentHelper;
  88322. })(BABYLON || (BABYLON = {}));
  88323. //# sourceMappingURL=babylon.environmentHelper.js.map
  88324. var BABYLON;
  88325. (function (BABYLON) {
  88326. /**
  88327. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  88328. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  88329. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  88330. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  88331. */
  88332. var VideoDome = /** @class */ (function (_super) {
  88333. __extends(VideoDome, _super);
  88334. /**
  88335. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  88336. * @param name Element's name, child elements will append suffixes for their own names.
  88337. * @param urlsOrVideo
  88338. * @param options An object containing optional or exposed sub element properties:
  88339. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  88340. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  88341. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  88342. * @param options **loop=true** Automatically loop video on end.
  88343. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  88344. */
  88345. function VideoDome(name, urlsOrVideo, options, scene) {
  88346. var _this = _super.call(this, name, scene) || this;
  88347. // set defaults and manage values
  88348. name = name || "videoDome";
  88349. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  88350. options.clickToPlay = Boolean(options.clickToPlay);
  88351. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  88352. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  88353. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  88354. // create
  88355. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  88356. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  88357. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  88358. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  88359. flat: false,
  88360. radius: options.size,
  88361. subdivisions: options.resolution,
  88362. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  88363. }, scene);
  88364. // configure material
  88365. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  88366. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  88367. material.reflectionTexture = _this._videoTexture;
  88368. material.useEquirectangularFOV = true;
  88369. material.fovMultiplier = 1.0;
  88370. // configure mesh
  88371. _this._mesh.material = material;
  88372. _this._mesh.parent = _this;
  88373. // optional configuration
  88374. if (options.clickToPlay) {
  88375. scene.onPointerUp = function () {
  88376. _this._videoTexture.video.play();
  88377. };
  88378. }
  88379. return _this;
  88380. }
  88381. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  88382. /**
  88383. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88384. * Also see the options.resolution property.
  88385. */
  88386. get: function () {
  88387. return this._material.fovMultiplier;
  88388. },
  88389. set: function (value) {
  88390. this._material.fovMultiplier = value;
  88391. },
  88392. enumerable: true,
  88393. configurable: true
  88394. });
  88395. return VideoDome;
  88396. }(BABYLON.Node));
  88397. BABYLON.VideoDome = VideoDome;
  88398. })(BABYLON || (BABYLON = {}));
  88399. //# sourceMappingURL=babylon.videoDome.js.map
  88400. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\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 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>\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#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}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\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\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>\nvoid main(void) {\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<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\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)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\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*vRefractionInfos.x;\n#endif\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*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\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*vReflectionInfos.x;\n#endif\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#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\ngl_FragColor=color;\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)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#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\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\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*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\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\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\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef 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\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\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\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\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\nvoid main() {\ngl_PointSize=1.0;\ngl_Position=vec4(position,1.0);\n}","gpuRenderParticlesPixelShader":"void main() {\ngl_FragColor=vec4(1.0);\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\nuniform float timeDelta;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec3 outVelocity;\nvoid main() {\nif (age>=life) {\n\noutPosition=vec3(0,0,0);\n\noutAge=0.0;\noutLife=life;\n\noutVelocity=vec3(0,1,0);\n} else {\noutPosition=position+velocity*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutVelocity=velocity;\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#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 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{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\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 vec2 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.y*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","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\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);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/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;\n}\ngl_FragColor=original;\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}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\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}","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}\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{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\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\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\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\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{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,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\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\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\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,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  88401. 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}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\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};\nuniform sampler2D shadowSampler{X};\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;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\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};\nuniform sampler2D shadowSampler{X};\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 computeShadowWithPCFCube(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 computeShadowWithPCF(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#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=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition );\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\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\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\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\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,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,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,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#else\n#ifdef 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#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,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#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)\n{\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,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);\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,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);\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,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);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  88402. globalObject["BABYLON"] = BABYLON;
  88403. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var VideoDome = BABYLON.VideoDome;
  88404. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,CircleOfConfusionPostProcess,DepthOfFieldMergePostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,VideoDome };